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