Skip to main content

rust_anything/lang/
python.rs

1//! Python: packages, imports, risks, the PyPI-to-crate table, and exported functions and
2//! classes with type hints mapped into the TS-like type dialect.
3
4use std::collections::{BTreeSet, HashMap};
5use std::path::Path;
6
7use anyhow::Result;
8use tree_sitter::Node;
9
10use super::syntax::{self, named_children, text};
11use crate::risks::{Risk, regex_needs_fancy};
12use crate::ts::deps::CrateMatch;
13use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
14use crate::ts::exports::{ExportedClass, ExportedFn, Param};
15use crate::ts::scan::{FileFacts, Import};
16
17fn language() -> tree_sitter::Language {
18    tree_sitter_python::LANGUAGE.into()
19}
20
21const SKIP_DIRS: &[&str] = &[
22    "node_modules",
23    "venv",
24    ".venv",
25    "env",
26    "__pycache__",
27    "build",
28    "dist",
29    "site-packages",
30    ".tox",
31    ".nox",
32    "target",
33    "fixtures",
34    "examples",
35    "docs",
36];
37
38// ---- discovery -------------------------------------------------------------------------------
39
40pub fn discover(root: &Path) -> Result<Workspace> {
41    let mut manifests = Vec::new();
42    let mut files = Vec::new();
43    let walker = crate::walk::filtered(root, |e| {
44        !(e.file_type().is_some_and(|t| t.is_dir())
45            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
46    })
47    .hidden(true)
48    .require_git(false)
49    .build();
50    for entry in walker.flatten() {
51        if !entry.file_type().is_some_and(|t| t.is_file()) {
52            continue;
53        }
54        let Ok(rel) = entry.path().strip_prefix(root) else {
55            continue;
56        };
57        let rel = rel.to_string_lossy().replace('\\', "/");
58        let name = rel.rsplit('/').next().unwrap_or(&rel);
59        if matches!(name, "pyproject.toml" | "setup.py" | "setup.cfg") {
60            let dir = rel
61                .rsplit_once('/')
62                .map_or(String::new(), |(d, _)| d.to_string());
63            if !manifests.contains(&dir) {
64                manifests.push(dir);
65            }
66        } else if name.ends_with(".py") && name != "setup.py" && name != "conftest.py" {
67            let is_test = name.starts_with("test_")
68                || name.ends_with("_test.py")
69                || rel
70                    .split('/')
71                    .any(|p| matches!(p, "tests" | "test" | "testing"));
72            files.push((
73                rel,
74                if is_test {
75                    FileKind::Test
76                } else {
77                    FileKind::Source
78                },
79            ));
80        }
81    }
82    let mut packages: Vec<Package> = manifests
83        .iter()
84        .map(|dir| read_package(root, dir))
85        .collect();
86    if !packages.iter().any(|p| p.dir.is_empty()) {
87        packages.push(Package {
88            name: root
89                .file_name()
90                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
91            dir: String::new(),
92            src_root: if root.join("src").is_dir() {
93                "src".into()
94            } else {
95                String::new()
96            },
97            deps: Vec::new(),
98            dev_deps: Vec::new(),
99        });
100    }
101    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
102    files.sort_by(|a, b| a.0.cmp(&b.0));
103    let files = files
104        .into_iter()
105        .map(|(path, kind)| {
106            let package = packages
107                .iter()
108                .enumerate()
109                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
110                .max_by_key(|(_, p)| p.dir.len())
111                .map_or(0, |(i, _)| i);
112            SourceFile {
113                path,
114                package,
115                kind,
116            }
117        })
118        .collect();
119    Ok(Workspace { packages, files })
120}
121
122fn read_package(root: &Path, dir: &str) -> Package {
123    let join = |name: &str| {
124        if dir.is_empty() {
125            name.to_string()
126        } else {
127            format!("{dir}/{name}")
128        }
129    };
130    let mut name = None;
131    let mut deps = Vec::new();
132    if let Ok(text) = std::fs::read_to_string(root.join(join("pyproject.toml")))
133        && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
134    {
135        name = doc
136            .get("project")
137            .and_then(|p| p.get("name"))
138            .and_then(|n| n.as_str())
139            .map(normalized_name);
140        if let Some(list) = doc
141            .get("project")
142            .and_then(|p| p.get("dependencies"))
143            .and_then(|d| d.as_array())
144        {
145            deps.extend(list.iter().filter_map(|d| d.as_str()).map(requirement_name));
146        }
147    }
148    if let Ok(text) = std::fs::read_to_string(root.join(join("requirements.txt"))) {
149        deps.extend(
150            text.lines()
151                .map(str::trim)
152                .filter(|l| !l.is_empty() && !l.starts_with('#'))
153                .map(requirement_name),
154        );
155    }
156    let src = join("src");
157    Package {
158        name: name.unwrap_or_else(|| {
159            if dir.is_empty() {
160                root.file_name()
161                    .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
162            } else {
163                dir.to_string()
164            }
165        }),
166        src_root: if root.join(&src).is_dir() {
167            src
168        } else {
169            dir.to_string()
170        },
171        dir: dir.to_string(),
172        deps,
173        dev_deps: Vec::new(),
174    }
175}
176
177/// `requests>=2.0; python_version>"3"` -> `requests`.
178fn requirement_name(line: &str) -> String {
179    normalized_name(
180        line.split(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_' || c == '.'))
181            .next()
182            .unwrap_or(""),
183    )
184}
185
186/// A distribution name as pip compares it (PEP 503): `Core_Lib.x` -> `core-lib-x`.
187fn normalized_name(name: &str) -> String {
188    name.split(['-', '_', '.'])
189        .filter(|part| !part.is_empty())
190        .collect::<Vec<_>>()
191        .join("-")
192        .to_lowercase()
193}
194
195// ---- scanning --------------------------------------------------------------------------------
196
197pub fn scan(source: &str) -> FileFacts {
198    let mut facts = FileFacts {
199        loc: syntax::loc(source),
200        ..FileFacts::default()
201    };
202    let Some(tree) = syntax::parse(&language(), source) else {
203        return facts;
204    };
205    let root = tree.root_node();
206    facts.parse_errors = usize::from(root.has_error());
207    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
208        facts
209            .risks
210            .entry(risk)
211            .or_default()
212            .push(syntax::line(node));
213    };
214    syntax::walk(root, |node| match node.kind() {
215        "import_statement" => {
216            for child in named_children(node) {
217                let name = child.child_by_field_name("name").unwrap_or(child);
218                facts.imports.push(Import {
219                    specifier: text(name, source).to_string(),
220                    type_only: false,
221                    dynamic: false,
222                });
223            }
224        }
225        "import_from_statement" => {
226            let Some(module) = node.child_by_field_name("module_name") else {
227                return;
228            };
229            let module = text(module, source).to_string();
230            facts.imports.push(Import {
231                specifier: module.clone(),
232                type_only: false,
233                dynamic: false,
234            });
235            // `from pkg import sub` may name a submodule.
236            let mut cursor = node.walk();
237            for name in node.children_by_field_name("name", &mut cursor) {
238                let name = name.child_by_field_name("name").unwrap_or(name);
239                let sep = if module.ends_with('.') { "" } else { "." };
240                facts.imports.push(Import {
241                    specifier: format!("{module}{sep}{}", text(name, source)),
242                    type_only: true,
243                    dynamic: false,
244                });
245            }
246        }
247        "call" => {
248            let Some(function) = node.child_by_field_name("function") else {
249                return;
250            };
251            let callee = text(function, source);
252            match callee {
253                "eval" | "exec" | "compile" | "__import__" | "importlib.import_module" => {
254                    add(&mut facts, Risk::DynamicCode, node)
255                }
256                "getattr" | "setattr" | "hasattr" | "delattr" | "isinstance" | "type" => {
257                    add(&mut facts, Risk::DynamicTyping, node);
258                }
259                "globals" | "locals" | "vars" => add(&mut facts, Risk::Reflection, node),
260                "set" | "frozenset" => add(&mut facts, Risk::UnorderedIteration, node),
261                "threading.Thread"
262                | "Thread"
263                | "ThreadPoolExecutor"
264                | "ProcessPoolExecutor"
265                | "asyncio.gather" => {
266                    add(&mut facts, Risk::Concurrency, node);
267                }
268                _ if callee.starts_with("re.") => {
269                    let pattern = node
270                        .child_by_field_name("arguments")
271                        .and_then(|a| named_children(a).into_iter().next())
272                        .filter(|a| a.kind() == "string");
273                    match pattern {
274                        Some(p) if regex_needs_fancy(text(p, source), "") => {
275                            add(&mut facts, Risk::RegexSyntax, node)
276                        }
277                        Some(_) => {}
278                        None => add(&mut facts, Risk::DynamicRegex, node),
279                    }
280                }
281                _ if callee.ends_with(".find")
282                    || callee.ends_with(".index")
283                    || callee.ends_with(".rfind") =>
284                {
285                    add(&mut facts, Risk::StringOffsets, node);
286                }
287                _ => {}
288            }
289        }
290        "subscript" if named_children(node).iter().any(|c| c.kind() == "slice") => {
291            add(&mut facts, Risk::StringOffsets, node)
292        }
293        "binary_operator" | "augmented_assignment" => {
294            let op = node
295                .child_by_field_name("operator")
296                .map_or("", |o| text(o, source));
297            match op {
298                "//" | "%" | "//=" | "%=" => add(&mut facts, Risk::DivisionSemantics, node),
299                "**" | "**=" | "<<" | "<<=" => add(&mut facts, Risk::IntegerSemantics, node),
300                "&" | "|" | "^" | ">>" => add(&mut facts, Risk::NumberSemantics, node),
301                _ => {}
302            }
303        }
304        "set" | "set_comprehension" => add(&mut facts, Risk::UnorderedIteration, node),
305        "decorator" if crate::risks::compiled_by(text(node, source)).is_some() => {
306            add(&mut facts, Risk::AlreadyCompiled, node)
307        }
308        "typed_parameter" | "typed_default_parameter"
309            if node.child_by_field_name("type").is_some_and(|t| {
310                let t = text(t, source);
311                t.contains("ndarray") || t.contains("NDArray")
312            }) =>
313        {
314            add(&mut facts, Risk::ArrayParameters, node)
315        }
316        "raise_statement" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
317        "yield" => add(&mut facts, Risk::Generators, node),
318        "await" => add(&mut facts, Risk::Async, node),
319        "for_statement"
320        | "while_statement"
321        | "list_comprehension"
322        | "dictionary_comprehension"
323        | "generator_expression" => {
324            facts.loops += 1;
325        }
326        "class_definition" if node.child_by_field_name("superclasses").is_some() => {
327            add(&mut facts, Risk::ClassInheritance, node)
328        }
329        "function_definition" => {
330            if text(node, source).starts_with("async") {
331                add(&mut facts, Risk::Async, node);
332            }
333            if node.child_by_field_name("parameters").is_some_and(|p| {
334                named_children(p).iter().any(|c| {
335                    c.kind() == "identifier"
336                        && text(*c, source) != "self"
337                        && text(*c, source) != "cls"
338                })
339            }) {
340                add(&mut facts, Risk::DynamicTyping, node);
341            }
342        }
343        "assignment" => {
344            // `Class.method = ...`, `module.attr = ...`: rewriting code at runtime.
345            let left = node
346                .child_by_field_name("left")
347                .map_or("", |l| text(l, source));
348            if left.contains('.')
349                && !left.starts_with("self.")
350                && left.chars().next().is_some_and(char::is_uppercase)
351            {
352                add(&mut facts, Risk::Monkeypatching, node);
353            }
354        }
355        _ => {}
356    });
357    facts
358}
359
360/// Where a Python import points.
361pub enum Resolution {
362    File(usize),
363    External(String),
364    Stdlib,
365    Unresolved,
366}
367
368/// Resolves `pkg.mod`, `.mod` and `..mod` against the files of the workspace.
369pub fn resolve(from: &str, spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> Resolution {
370    let try_module = |base: &str| -> Option<usize> {
371        let base = base.trim_matches('/');
372        [format!("{base}.py"), format!("{base}/__init__.py")]
373            .iter()
374            .find_map(|c| index.get(c.as_str()).copied())
375    };
376    if spec.starts_with('.') {
377        let dots = spec.chars().take_while(|c| *c == '.').count();
378        let mut dir: Vec<&str> = from.split('/').collect();
379        dir.pop();
380        for _ in 1..dots {
381            dir.pop();
382        }
383        let rest = spec[dots..].replace('.', "/");
384        let base = if rest.is_empty() {
385            dir.join("/")
386        } else {
387            format!("{}/{rest}", dir.join("/"))
388        };
389        return try_module(&base).map_or(Resolution::Unresolved, Resolution::File);
390    }
391    let path = spec.replace('.', "/");
392    let roots: BTreeSet<&str> = ws
393        .packages
394        .iter()
395        .map(|p| p.src_root.as_str())
396        .chain([""])
397        .collect();
398    for root in roots {
399        let base = if root.is_empty() {
400            path.clone()
401        } else {
402            format!("{root}/{path}")
403        };
404        if let Some(i) = try_module(&base) {
405            return Resolution::File(i);
406        }
407    }
408    let top = spec.split('.').next().unwrap_or(spec);
409    if STDLIB.contains(&top) {
410        Resolution::Stdlib
411    } else if index
412        .keys()
413        .any(|p| p.starts_with(&format!("{top}/")) || p.contains(&format!("/{top}/")))
414    {
415        // A local package imported by a shorter path than its files: still local.
416        Resolution::Unresolved
417    } else {
418        Resolution::External(top.to_lowercase().replace('_', "-"))
419    }
420}
421
422// The version-agnostic list includes Python 3.12 modules removed in 3.13;
423// imports of their backports can therefore also resolve as stdlib.
424const STDLIB: &[&str] = &[
425    "__future__",
426    "__main__",
427    "_abc",
428    "_aix_support",
429    "_ast",
430    "_asyncio",
431    "_bisect",
432    "_blake2",
433    "_bz2",
434    "_codecs",
435    "_codecs_cn",
436    "_codecs_hk",
437    "_codecs_iso2022",
438    "_codecs_jp",
439    "_codecs_kr",
440    "_codecs_tw",
441    "_collections",
442    "_collections_abc",
443    "_compat_pickle",
444    "_compression",
445    "_contextvars",
446    "_crypt",
447    "_csv",
448    "_ctypes",
449    "_curses",
450    "_curses_panel",
451    "_datetime",
452    "_dbm",
453    "_decimal",
454    "_elementtree",
455    "_frozen_importlib",
456    "_frozen_importlib_external",
457    "_functools",
458    "_gdbm",
459    "_hashlib",
460    "_heapq",
461    "_imp",
462    "_io",
463    "_json",
464    "_locale",
465    "_lsprof",
466    "_lzma",
467    "_markupbase",
468    "_md5",
469    "_msi",
470    "_multibytecodec",
471    "_multiprocessing",
472    "_opcode",
473    "_operator",
474    "_osx_support",
475    "_overlapped",
476    "_pickle",
477    "_posixshmem",
478    "_posixsubprocess",
479    "_py_abc",
480    "_pydatetime",
481    "_pydecimal",
482    "_pyio",
483    "_pylong",
484    "_queue",
485    "_random",
486    "_scproxy",
487    "_sha1",
488    "_sha2",
489    "_sha3",
490    "_signal",
491    "_sitebuiltins",
492    "_socket",
493    "_sqlite3",
494    "_sre",
495    "_ssl",
496    "_stat",
497    "_statistics",
498    "_string",
499    "_strptime",
500    "_struct",
501    "_symtable",
502    "_thread",
503    "_threading_local",
504    "_tkinter",
505    "_tokenize",
506    "_tracemalloc",
507    "_typing",
508    "_uuid",
509    "_warnings",
510    "_weakref",
511    "_weakrefset",
512    "_winapi",
513    "_wmi",
514    "_zoneinfo",
515    "abc",
516    "aifc",
517    "antigravity",
518    "argparse",
519    "array",
520    "ast",
521    "asyncio",
522    "atexit",
523    "audioop",
524    "base64",
525    "bdb",
526    "binascii",
527    "bisect",
528    "builtins",
529    "bz2",
530    "calendar",
531    "cgi",
532    "cgitb",
533    "chunk",
534    "cmath",
535    "cmd",
536    "code",
537    "codecs",
538    "codeop",
539    "collections",
540    "colorsys",
541    "compileall",
542    "concurrent",
543    "configparser",
544    "contextlib",
545    "contextvars",
546    "copy",
547    "copyreg",
548    "cProfile",
549    "crypt",
550    "csv",
551    "ctypes",
552    "curses",
553    "dataclasses",
554    "datetime",
555    "dbm",
556    "decimal",
557    "difflib",
558    "dis",
559    "doctest",
560    "email",
561    "encodings",
562    "ensurepip",
563    "enum",
564    "errno",
565    "faulthandler",
566    "fcntl",
567    "filecmp",
568    "fileinput",
569    "fnmatch",
570    "fractions",
571    "ftplib",
572    "functools",
573    "gc",
574    "genericpath",
575    "getopt",
576    "getpass",
577    "gettext",
578    "glob",
579    "graphlib",
580    "grp",
581    "gzip",
582    "hashlib",
583    "heapq",
584    "hmac",
585    "html",
586    "http",
587    "idlelib",
588    "imaplib",
589    "imghdr",
590    "importlib",
591    "inspect",
592    "io",
593    "ipaddress",
594    "itertools",
595    "json",
596    "keyword",
597    "lib2to3",
598    "linecache",
599    "locale",
600    "logging",
601    "lzma",
602    "mailbox",
603    "mailcap",
604    "marshal",
605    "math",
606    "mimetypes",
607    "mmap",
608    "modulefinder",
609    "msilib",
610    "msvcrt",
611    "multiprocessing",
612    "netrc",
613    "nis",
614    "nntplib",
615    "nt",
616    "ntpath",
617    "nturl2path",
618    "numbers",
619    "opcode",
620    "operator",
621    "optparse",
622    "os",
623    "ossaudiodev",
624    "pathlib",
625    "pdb",
626    "pickle",
627    "pickletools",
628    "pipes",
629    "pkgutil",
630    "platform",
631    "plistlib",
632    "poplib",
633    "posix",
634    "posixpath",
635    "pprint",
636    "profile",
637    "pstats",
638    "pty",
639    "pwd",
640    "py_compile",
641    "pyclbr",
642    "pydoc",
643    "pydoc_data",
644    "pyexpat",
645    "queue",
646    "quopri",
647    "random",
648    "re",
649    "readline",
650    "reprlib",
651    "resource",
652    "rlcompleter",
653    "runpy",
654    "sched",
655    "secrets",
656    "select",
657    "selectors",
658    "shelve",
659    "shlex",
660    "shutil",
661    "signal",
662    "site",
663    "smtplib",
664    "sndhdr",
665    "socket",
666    "socketserver",
667    "spwd",
668    "sqlite3",
669    "sre_compile",
670    "sre_constants",
671    "sre_parse",
672    "ssl",
673    "stat",
674    "statistics",
675    "string",
676    "stringprep",
677    "struct",
678    "subprocess",
679    "sunau",
680    "symtable",
681    "sys",
682    "sysconfig",
683    "syslog",
684    "tabnanny",
685    "tarfile",
686    "telnetlib",
687    "tempfile",
688    "termios",
689    "test",
690    "textwrap",
691    "this",
692    "threading",
693    "time",
694    "timeit",
695    "tkinter",
696    "token",
697    "tokenize",
698    "tomllib",
699    "trace",
700    "traceback",
701    "tracemalloc",
702    "tty",
703    "turtle",
704    "turtledemo",
705    "types",
706    "typing",
707    "typing_extensions",
708    "unicodedata",
709    "unittest",
710    "urllib",
711    "uu",
712    "uuid",
713    "venv",
714    "warnings",
715    "wave",
716    "weakref",
717    "webbrowser",
718    "winreg",
719    "winsound",
720    "wsgiref",
721    "xdrlib",
722    "xml",
723    "xmlrpc",
724    "zipapp",
725    "zipfile",
726    "zipimport",
727    "zlib",
728    "zoneinfo",
729];
730
731// ---- dependencies ----------------------------------------------------------------------------
732
733/// The Rust counterpart of a PyPI package (or import name).
734pub fn lookup(package: &str) -> Option<CrateMatch> {
735    crate::crates::find("python", package)
736}
737
738// ---- exports ---------------------------------------------------------------------------------
739
740/// Decorators that keep a function's behavior as seen by callers.
741const SAFE_DECORATORS: &[&str] = &[
742    "cache",
743    "lru_cache",
744    "functools.cache",
745    "functools.lru_cache",
746    "staticmethod",
747];
748
749/// Public module-level functions and classes, honoring `__all__`.
750pub fn exports(path: &str, source: &str) -> (Vec<ExportedFn>, Vec<ExportedClass>) {
751    let Some(tree) = syntax::parse(&language(), source) else {
752        return (Vec::new(), Vec::new());
753    };
754    let root = tree.root_node();
755    let all = dunder_all(root, source);
756    let public = |name: &str| {
757        all.as_ref().map_or(!name.starts_with('_'), |names| {
758            names.iter().any(|n| n == name)
759        })
760    };
761    let entry = entry_calls(root, source, path.ends_with("__main__.py"));
762    let mut functions = Vec::new();
763    let mut classes = Vec::new();
764    for item in named_children(root) {
765        let (decorators, definition) = unwrap_decorated(item, source);
766        match definition.kind() {
767            "function_definition" => {
768                let Some(mut f) = function(path, definition, source, &decorators, false) else {
769                    continue;
770                };
771                let parser = definition
772                    .child_by_field_name("return_type")
773                    .is_some_and(|t| text(t, source).ends_with("ArgumentParser"));
774                if parser || entry.iter().any(|n| *n == f.name) {
775                    f.blocker = Some(
776                        "a command-line entry point: it stays in Python, and `app front-door` \
777                         takes the command line over when the whole app moves"
778                            .into(),
779                    );
780                }
781                if public(&f.name) {
782                    functions.push(f);
783                }
784            }
785            "class_definition" => {
786                let Some(c) = class(path, definition, source, &decorators) else {
787                    continue;
788                };
789                if public(&c.name) {
790                    classes.push(c);
791                }
792            }
793            _ => {}
794        }
795    }
796    (functions, classes)
797}
798
799/// Dataclasses declared at the top level of a file, as types `record` can build values of:
800/// `{ $object: "Name"; attrs: { field: type; defaulted?: type } }`, which the Python driver
801/// turns into an instance of the class.
802pub fn dataclass_types(source: &str) -> Vec<crate::ts::exports::LocalType> {
803    let Some(tree) = syntax::parse(&language(), source) else {
804        return Vec::new();
805    };
806    let mut out = Vec::new();
807    for item in named_children(tree.root_node()) {
808        let (decorators, definition) = unwrap_decorated(item, source);
809        if definition.kind() != "class_definition"
810            || !decorators.iter().any(|d| d.contains("dataclass"))
811        {
812            continue;
813        }
814        let Some(name) = definition.child_by_field_name("name") else {
815            continue;
816        };
817        let mut fields = Vec::new();
818        if let Some(body) = definition.child_by_field_name("body") {
819            for statement in named_children(body) {
820                let Some(assignment) = named_children(statement)
821                    .into_iter()
822                    .find(|n| n.kind() == "assignment")
823                else {
824                    continue;
825                };
826                let (Some(left), Some(ty)) = (
827                    assignment.child_by_field_name("left"),
828                    assignment.child_by_field_name("type"),
829                ) else {
830                    continue;
831                };
832                let hint = text(ty, source);
833                if hint.starts_with("ClassVar") || hint.starts_with("typing.ClassVar") {
834                    continue;
835                }
836                let optional = if assignment.child_by_field_name("right").is_some() {
837                    "?"
838                } else {
839                    ""
840                };
841                fields.push(format!(
842                    "{}{optional}: {}",
843                    text(left, source),
844                    to_ts_type(hint)
845                ));
846            }
847        }
848        let name = text(name, source).to_string();
849        out.push(crate::ts::exports::LocalType {
850            text: format!(
851                "{{ $object: {name:?}; attrs: {{ {} }} }}",
852                fields.join("; ")
853            ),
854            name,
855            alias: true,
856        });
857    }
858    out
859}
860
861/// Functions the file runs as a program: the calls inside `if __name__ == "__main__":`, or
862/// every top-level call in a package's `__main__.py`.
863fn entry_calls<'s>(root: Node, source: &'s str, main_module: bool) -> Vec<&'s str> {
864    let mut out = Vec::new();
865    let mut collect = |node: Node| {
866        syntax::walk(node, |n| {
867            if n.kind() == "call"
868                && let Some(f) = n.child_by_field_name("function")
869                && f.kind() == "identifier"
870            {
871                out.push(text(f, source));
872            }
873        });
874    };
875    for statement in named_children(root) {
876        let guard = statement.kind() == "if_statement"
877            && statement.child_by_field_name("condition").is_some_and(|c| {
878                let c = text(c, source).replace(' ', "").replace('\'', "\"");
879                c == "__name__==\"__main__\"" || c == "\"__main__\"==__name__"
880            });
881        if guard {
882            if let Some(body) = statement.child_by_field_name("consequence") {
883                collect(body);
884            }
885        } else if main_module && statement.kind() == "expression_statement" {
886            collect(statement);
887        }
888    }
889    out
890}
891
892fn dunder_all(root: Node, source: &str) -> Option<Vec<String>> {
893    for statement in named_children(root) {
894        let assignment = named_children(statement)
895            .into_iter()
896            .find(|n| n.kind() == "assignment")?;
897        if assignment
898            .child_by_field_name("left")
899            .map(|l| text(l, source))
900            == Some("__all__")
901        {
902            let right = assignment.child_by_field_name("right")?;
903            return Some(
904                named_children(right)
905                    .into_iter()
906                    .filter(|n| n.kind() == "string")
907                    .map(|n| {
908                        text(n, source)
909                            .trim_matches(|c| c == '"' || c == '\'')
910                            .to_string()
911                    })
912                    .collect(),
913            );
914        }
915    }
916    None
917}
918
919fn unwrap_decorated<'t>(node: Node<'t>, source: &str) -> (Vec<String>, Node<'t>) {
920    if node.kind() != "decorated_definition" {
921        return (Vec::new(), node);
922    }
923    let decorators = named_children(node)
924        .into_iter()
925        .filter(|n| n.kind() == "decorator")
926        .map(|d| {
927            let t = text(d, source).trim_start_matches('@').trim();
928            t.split('(').next().unwrap_or(t).to_string()
929        })
930        .collect();
931    (
932        decorators,
933        node.child_by_field_name("definition").unwrap_or(node),
934    )
935}
936
937/// Unannotated parameters the body uses as numbers (`r - g`, `x * 0.5`, `max(r, g)`, `x < 1`)
938/// become `number`: generated inputs then fit what the code expects.
939pub fn infer_numbers(params: &mut [Param], body: Node, source: &str) {
940    let unknown: Vec<String> = params
941        .iter()
942        .filter(|p| p.ts_type == "unknown" && p.default.is_none())
943        .map(|p| p.name.clone())
944        .collect();
945    if unknown.is_empty() {
946        return;
947    }
948    let mut numeric: Vec<String> = Vec::new();
949    let is_number = |n: Node| matches!(n.kind(), "integer" | "float");
950    syntax::walk(body, |n| {
951        let operands: Vec<Node> = match n.kind() {
952            "binary_operator" => {
953                let op = n
954                    .child_by_field_name("operator")
955                    .map_or("", |o| text(o, source));
956                let (Some(l), Some(r)) = (
957                    n.child_by_field_name("left"),
958                    n.child_by_field_name("right"),
959                ) else {
960                    return;
961                };
962                match op {
963                    "-" | "*" | "/" | "//" | "**" => vec![l, r],
964                    "+" | "%" if is_number(l) || is_number(r) => vec![l, r],
965                    _ => return,
966                }
967            }
968            "comparison_operator" => {
969                let parts = named_children(n);
970                if !parts.iter().any(|p| is_number(*p)) {
971                    return;
972                }
973                parts
974            }
975            "call" => {
976                let f = n
977                    .child_by_field_name("function")
978                    .map_or("", |f| text(f, source));
979                if !matches!(
980                    f,
981                    "min" | "max" | "abs" | "round" | "float" | "int" | "divmod"
982                ) && !f.starts_with("math.")
983                {
984                    return;
985                }
986                n.child_by_field_name("arguments")
987                    .map(named_children)
988                    .unwrap_or_default()
989            }
990            _ => return,
991        };
992        for o in operands {
993            if o.kind() == "identifier" {
994                let name = text(o, source).to_string();
995                if unknown.contains(&name) && !numeric.contains(&name) {
996                    numeric.push(name);
997                }
998            }
999        }
1000    });
1001    for p in params.iter_mut().filter(|p| numeric.contains(&p.name)) {
1002        p.ts_type = "number".into();
1003    }
1004}
1005
1006fn function(
1007    path: &str,
1008    node: Node,
1009    source: &str,
1010    decorators: &[String],
1011    method: bool,
1012) -> Option<ExportedFn> {
1013    let name = text(node.child_by_field_name("name")?, source).to_string();
1014    let (mut params, mut blocker) =
1015        parameters(node.child_by_field_name("parameters")?, source, method);
1016    let body = node.child_by_field_name("body");
1017    if let Some(body) = body {
1018        infer_numbers(&mut params, body, source);
1019    }
1020    let mut generator = false;
1021    if let Some(body) = body {
1022        syntax::walk(body, |n| {
1023            if n.kind() == "yield" {
1024                generator = true;
1025            }
1026        });
1027    }
1028    // An untyped parameter that the body calls is a callable: it cannot cross a bridge.
1029    if let Some(body) = body {
1030        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
1031        syntax::walk(body, |n| {
1032            if n.kind() == "call"
1033                && let Some(f) = n.child_by_field_name("function")
1034                && f.kind() == "identifier"
1035                && names.contains(&text(f, source))
1036                && blocker.is_none()
1037            {
1038                blocker = Some(format!(
1039                    "calls its parameter `{}`: a callable",
1040                    text(f, source)
1041                ));
1042            }
1043        });
1044    }
1045    if let Some(d) = decorators
1046        .iter()
1047        .find(|d| !SAFE_DECORATORS.contains(&d.as_str()))
1048    {
1049        blocker = blocker.or_else(|| Some(format!("decorated with `@{d}`")));
1050    }
1051    Some(ExportedFn {
1052        name,
1053        file: path.to_string(),
1054        line: syntax::line(node),
1055        params,
1056        returns: node
1057            .child_by_field_name("return_type")
1058            .map_or_else(|| "unknown".into(), |r| to_ts_type(text(r, source))),
1059        is_async: text(node, source).starts_with("async"),
1060        is_generator: generator,
1061        blocker,
1062        ..Default::default()
1063    })
1064}
1065
1066/// Parameters in the type dialect, and a reason when the signature cannot cross a bridge.
1067fn parameters(node: Node, source: &str, method: bool) -> (Vec<Param>, Option<String>) {
1068    let mut params = Vec::new();
1069    let mut blocker = None;
1070    let mut keyword_only = false;
1071    for (i, p) in named_children(node).into_iter().enumerate() {
1072        let name = |n: Option<Node>| n.map(|n| text(n, source).to_string()).unwrap_or_default();
1073        let param = match p.kind() {
1074            "identifier" => Param {
1075                name: text(p, source).into(),
1076                ts_type: "unknown".into(),
1077                ..Default::default()
1078            },
1079            "typed_parameter" => {
1080                let inner = named_children(p).into_iter().next();
1081                let ty = p
1082                    .child_by_field_name("type")
1083                    .map_or_else(|| "unknown".into(), |t| to_ts_type(text(t, source)));
1084                match inner.map(|n| n.kind()) {
1085                    Some("list_splat_pattern") => {
1086                        blocker = Some("takes `*args`".into());
1087                        continue;
1088                    }
1089                    Some("dictionary_splat_pattern") => {
1090                        blocker = Some("takes `**kwargs`".into());
1091                        continue;
1092                    }
1093                    _ => Param {
1094                        name: name(inner),
1095                        ts_type: ty,
1096                        ..Default::default()
1097                    },
1098                }
1099            }
1100            "default_parameter" | "typed_default_parameter" => {
1101                let value = p.child_by_field_name("value");
1102                let default = value.map(|v| text(v, source).to_string());
1103                let ty = match p.child_by_field_name("type") {
1104                    Some(t) => to_ts_type(text(t, source)),
1105                    None => match value.map(|v| v.kind()) {
1106                        Some("integer") => "int".into(),
1107                        Some("float") => "number".into(),
1108                        Some("string") => "string".into(),
1109                        Some("true" | "false") => "boolean".into(),
1110                        _ => "unknown".into(),
1111                    },
1112                };
1113                Param {
1114                    name: name(p.child_by_field_name("name")),
1115                    ts_type: ty,
1116                    optional: true,
1117                    default,
1118                    ..Default::default()
1119                }
1120            }
1121            "list_splat_pattern" => {
1122                blocker = Some("takes `*args`".into());
1123                continue;
1124            }
1125            "dictionary_splat_pattern" => {
1126                blocker = Some("takes `**kwargs`".into());
1127                continue;
1128            }
1129            "keyword_separator" => {
1130                keyword_only = true;
1131                continue;
1132            }
1133            _ => continue,
1134        };
1135        if method && i == 0 && (param.name == "self" || param.name == "cls") {
1136            continue;
1137        }
1138        params.push(Param {
1139            keyword_only,
1140            ..param
1141        });
1142    }
1143    (params, blocker)
1144}
1145
1146fn class(path: &str, node: Node, source: &str, decorators: &[String]) -> Option<ExportedClass> {
1147    let name = text(node.child_by_field_name("name")?, source).to_string();
1148    let mut blockers = Vec::new();
1149    if let Some(bases) = node.child_by_field_name("superclasses") {
1150        let bases: Vec<&str> = named_children(bases)
1151            .into_iter()
1152            .map(|b| text(b, source))
1153            .filter(|b| *b != "object")
1154            .collect();
1155        if !bases.is_empty() {
1156            blockers.push(format!("inherits from {}", bases.join(", ")));
1157        }
1158    }
1159    if let Some(d) = decorators.first() {
1160        blockers.push(format!("decorated with `@{d}`"));
1161    }
1162    let mut constructor = Vec::new();
1163    let mut methods = Vec::new();
1164    for item in named_children(node.child_by_field_name("body")?) {
1165        let (decorators, definition) = unwrap_decorated(item, source);
1166        match definition.kind() {
1167            "function_definition" => {
1168                let method_name = definition
1169                    .child_by_field_name("name")
1170                    .map_or("", |n| text(n, source));
1171                if method_name == "__init__" {
1172                    let (params, blocker) =
1173                        parameters(definition.child_by_field_name("parameters")?, source, true);
1174                    constructor = params;
1175                    blockers.extend(blocker);
1176                    // `self.name = ...` with a public name: callers can read the attribute.
1177                    if let Some(body) = definition.child_by_field_name("body") {
1178                        syntax::walk(body, |n| {
1179                            if n.kind() == "assignment"
1180                                && let Some(left) = n.child_by_field_name("left")
1181                                && let Some(attr) = text(left, source).strip_prefix("self.")
1182                                && !attr.starts_with('_')
1183                                && !attr.contains('.')
1184                            {
1185                                blockers.push(format!("public attribute `{attr}`"));
1186                            }
1187                        });
1188                    }
1189                } else if method_name.starts_with("__") && method_name.ends_with("__") {
1190                    blockers.push(format!("special method `{method_name}`"));
1191                } else if method_name.starts_with('_') {
1192                } else if let Some(d) = decorators.first() {
1193                    blockers.push(format!("`@{d}` method `{method_name}`"));
1194                } else if let Some(f) = function(path, definition, source, &[], true) {
1195                    if f.is_async || f.is_generator {
1196                        blockers.push(format!("async or generator method `{}`", f.name));
1197                    }
1198                    if f.returns
1199                        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
1200                        .any(|w| w == name || w == "Self")
1201                    {
1202                        blockers.push(format!("method `{}` returns an instance", f.name));
1203                    }
1204                    methods.push(f);
1205                }
1206            }
1207            "expression_statement" => {
1208                let assignment = named_children(definition)
1209                    .into_iter()
1210                    .find(|n| n.kind() == "assignment");
1211                if let Some(left) = assignment.and_then(|a| a.child_by_field_name("left")) {
1212                    let attr = text(left, source);
1213                    if !attr.starts_with('_') {
1214                        blockers.push(format!("public class attribute `{attr}`"));
1215                    }
1216                }
1217            }
1218            _ => {}
1219        }
1220    }
1221    blockers.sort();
1222    blockers.dedup();
1223    Some(ExportedClass {
1224        name,
1225        file: path.to_string(),
1226        line: syntax::line(node),
1227        constructor,
1228        methods,
1229        blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
1230    })
1231}
1232
1233/// A Python type hint in the TS-like dialect: `list[str]` -> `string[]`, `Optional[int]` ->
1234/// `int | undefined`, `Callable[...]` -> a function type (which keeps the export in Python).
1235pub fn to_ts_type(hint: &str) -> String {
1236    let hint = hint.trim().trim_matches(|c| c == '"' || c == '\'');
1237    let hint = hint.strip_prefix("typing.").unwrap_or(hint);
1238    let top = split_top(hint, '|');
1239    if top.len() > 1 {
1240        return top
1241            .iter()
1242            .map(|p| to_ts_type(p))
1243            .collect::<Vec<_>>()
1244            .join(" | ");
1245    }
1246    let (head, args) = match hint.find('[') {
1247        Some(i) if hint.ends_with(']') => {
1248            (&hint[..i], split_top(&hint[i + 1..hint.len() - 1], ','))
1249        }
1250        _ => (hint, Vec::new()),
1251    };
1252    let head = head.trim().strip_prefix("typing.").unwrap_or(head.trim());
1253    let arg = |i: usize| {
1254        args.get(i)
1255            .map_or_else(|| "unknown".to_string(), |a| to_ts_type(a))
1256    };
1257    match head {
1258        "str" => "string".into(),
1259        "int" => "int".into(),
1260        "float" => "number".into(),
1261        "bool" => "boolean".into(),
1262        "None" | "NoneType" => "undefined".into(),
1263        "list" | "List" | "Sequence" | "Iterable" | "MutableSequence" | "Collection" => {
1264            format!("{}[]", wrap(&arg(0)))
1265        }
1266        "Optional" => format!("{} | undefined", arg(0)),
1267        "Union" => args
1268            .iter()
1269            .map(|a| to_ts_type(a))
1270            .collect::<Vec<_>>()
1271            .join(" | "),
1272        "dict" | "Dict" | "Mapping" | "MutableMapping" if arg(0) == "string" => {
1273            format!("Record<string, {}>", arg(1))
1274        }
1275        "Literal" => args
1276            .iter()
1277            .map(|a| a.trim().replace('"', "'"))
1278            .collect::<Vec<_>>()
1279            .join(" | "),
1280        "Callable" => "(...args: unknown[]) => unknown".into(),
1281        "Any" | "object" => "unknown".into(),
1282        // Tuples, sets, bytes, other dicts and named classes cross as JSON.
1283        other => other.to_string(),
1284    }
1285}
1286
1287fn wrap(ts: &str) -> String {
1288    if ts.contains('|') {
1289        format!("({ts})")
1290    } else {
1291        ts.to_string()
1292    }
1293}
1294
1295fn split_top(text: &str, sep: char) -> Vec<String> {
1296    let mut out = Vec::new();
1297    let mut depth = 0i32;
1298    let mut current = String::new();
1299    for c in text.chars() {
1300        match c {
1301            '[' | '(' => depth += 1,
1302            ']' | ')' => depth -= 1,
1303            _ => {}
1304        }
1305        if c == sep && depth == 0 {
1306            out.push(current.trim().to_string());
1307            current.clear();
1308        } else {
1309            current.push(c);
1310        }
1311    }
1312    if !current.trim().is_empty() {
1313        out.push(current.trim().to_string());
1314    }
1315    out
1316}
1317
1318#[cfg(test)]
1319mod tests {
1320    use super::*;
1321
1322    #[test]
1323    fn maps_type_hints() {
1324        assert_eq!(to_ts_type("list[str]"), "string[]");
1325        assert_eq!(to_ts_type("Optional[int]"), "int | undefined");
1326        assert_eq!(to_ts_type("str | None"), "string | undefined");
1327        assert_eq!(
1328            to_ts_type("dict[str, list[float]]"),
1329            "Record<string, number[]>"
1330        );
1331        assert_eq!(to_ts_type("Literal['a', \"b\"]"), "'a' | 'b'");
1332        assert!(to_ts_type("Callable[[int], str]").contains("=>"));
1333        assert_eq!(to_ts_type("tuple[int, int]"), "tuple");
1334    }
1335
1336    #[test]
1337    fn unix_stdlib_is_not_external() {
1338        // `import fcntl` in a pure-Python package must not surface as an unknown
1339        // (npm) dependency: it is Unix stdlib with no PyPI counterpart to look up.
1340        for module in [
1341            "fcntl", "termios", "resource", "grp", "pwd", "posix", "syslog",
1342        ] {
1343            assert!(
1344                STDLIB.contains(&module),
1345                "{module} should resolve as stdlib"
1346            );
1347        }
1348    }
1349
1350    #[test]
1351    fn standard_library_imports_resolve_without_dependencies() {
1352        let ws = Workspace {
1353            packages: vec![],
1354            files: vec![],
1355        };
1356        let index = HashMap::new();
1357        for module in [
1358            "faulthandler",
1359            "site",
1360            "bdb",
1361            "graphlib",
1362            "_thread",
1363            "telnetlib",
1364            "cgi",
1365        ] {
1366            assert!(
1367                matches!(resolve("main.py", module, &index, &ws), Resolution::Stdlib),
1368                "{module}"
1369            );
1370        }
1371        assert!(matches!(
1372            resolve("main.py", "requests", &index, &ws),
1373            Resolution::External(_)
1374        ));
1375        let local = HashMap::from([("site.py", 0)]);
1376        assert!(matches!(
1377            resolve("main.py", "site", &local, &ws),
1378            Resolution::File(0)
1379        ));
1380    }
1381
1382    #[test]
1383    fn reads_exports() {
1384        let source = "__all__ = ['slug', 'Counter']\n\n\
1385            def slug(text: str, sep: str = '-', *, lower=True) -> str:\n    return text\n\n\
1386            def hidden(x): pass\n\n\
1387            @lru_cache\ndef cached(n: int) -> int:\n    return n\n\n\
1388            def gen(n: int):\n    yield n\n\n\
1389            class Counter:\n    def __init__(self, start: int = 0):\n        self._n = start\n    def add(self, k: int) -> int:\n        return k\n    def _p(self): pass\n\n\
1390            class Point:\n    def __init__(self, x):\n        self.x = x\n";
1391        let (functions, classes) = exports("m.py", source);
1392        assert_eq!(
1393            functions
1394                .iter()
1395                .map(|f| f.name.as_str())
1396                .collect::<Vec<_>>(),
1397            ["slug"]
1398        );
1399        let slug = &functions[0];
1400        assert_eq!(slug.params[1].default.as_deref(), Some("'-'"));
1401        assert!(slug.params[2].keyword_only && slug.params[2].ts_type == "boolean");
1402        assert_eq!(slug.returns, "string");
1403        assert_eq!(classes.len(), 1);
1404        assert!(classes[0].blocker.is_none());
1405        assert_eq!(classes[0].methods.len(), 1);
1406
1407        let (all, classes) = exports(
1408            "n.py",
1409            &source.replace("__all__ = ['slug', 'Counter']\n", ""),
1410        );
1411        let names: Vec<&str> = all.iter().map(|f| f.name.as_str()).collect();
1412        assert_eq!(names, ["slug", "hidden", "cached", "gen"]);
1413        assert!(all[3].is_generator);
1414        assert!(
1415            classes[1]
1416                .blocker
1417                .as_deref()
1418                .unwrap()
1419                .contains("public attribute `x`")
1420        );
1421    }
1422
1423    #[test]
1424    fn scans_risks_and_imports() {
1425        let facts = scan(
1426            "import os\nfrom .util import helper\nimport re\nx = 7 // 2\nre.compile(r'(?<=a)b')\nfor i in range(3): pass\n",
1427        );
1428        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1429        assert!(
1430            specs.contains(&"os") && specs.contains(&".util") && specs.contains(&".util.helper")
1431        );
1432        assert!(facts.risks.contains_key(&Risk::DivisionSemantics));
1433        assert!(facts.risks.contains_key(&Risk::RegexSyntax));
1434        assert_eq!(facts.loops, 1);
1435    }
1436
1437    #[test]
1438    fn infers_numbers_from_arithmetic() {
1439        let src = "def rgb_to_hsv(r, g, b):\n    maxc = max(r, g, b)\n    return maxc - r\n\n\
1440                   def greet(name):\n    return 'hi ' + name\n";
1441        let (fns, _) = exports("colorsys.py", src);
1442        let types: Vec<&str> = fns[0].params.iter().map(|p| p.ts_type.as_str()).collect();
1443        assert_eq!(types, ["number", "number", "number"]);
1444        assert_eq!(fns[1].params[0].ts_type, "unknown");
1445    }
1446}