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