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, crate::lang::Lang::Python),
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                "&" | "|" | "^" | ">>" | "&=" | "|=" | "^=" | ">>=" => {
359                    add(&mut facts, Risk::NumberSemantics, node)
360                }
361                _ => {}
362            }
363        }
364        "set" | "set_comprehension" => add(&mut facts, Risk::UnorderedIteration, node),
365        "decorator" if crate::risks::compiled_by(text(node, source)).is_some() => {
366            add(&mut facts, Risk::AlreadyCompiled, node)
367        }
368        "typed_parameter" | "typed_default_parameter"
369            if node.child_by_field_name("type").is_some_and(|t| {
370                let t = text(t, source);
371                t.contains("ndarray") || t.contains("NDArray")
372            }) =>
373        {
374            add(&mut facts, Risk::ArrayParameters, node)
375        }
376        "raise_statement" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
377        "yield" => add(&mut facts, Risk::Generators, node),
378        "await" => add(&mut facts, Risk::Async, node),
379        "for_statement"
380        | "while_statement"
381        | "list_comprehension"
382        | "dictionary_comprehension"
383        | "generator_expression" => {
384            facts.loops += 1;
385        }
386        "class_definition" if node.child_by_field_name("superclasses").is_some() => {
387            add(&mut facts, Risk::ClassInheritance, node)
388        }
389        "function_definition" => {
390            if text(node, source).starts_with("async") {
391                add(&mut facts, Risk::Async, node);
392            }
393            if node.child_by_field_name("parameters").is_some_and(|p| {
394                named_children(p).iter().any(|c| {
395                    c.kind() == "identifier"
396                        && text(*c, source) != "self"
397                        && text(*c, source) != "cls"
398                })
399            }) {
400                add(&mut facts, Risk::DynamicTyping, node);
401            }
402        }
403        "assignment" => {
404            // `Class.method = ...`, `module.attr = ...`: rewriting code at runtime.
405            let left = node
406                .child_by_field_name("left")
407                .map_or("", |l| text(l, source));
408            if left.contains('.')
409                && !left.starts_with("self.")
410                && left.chars().next().is_some_and(char::is_uppercase)
411            {
412                add(&mut facts, Risk::Monkeypatching, node);
413            }
414        }
415        _ => {}
416    });
417    facts
418}
419
420/// Where a Python import points.
421pub enum Resolution {
422    File(usize),
423    External(String),
424    Stdlib,
425    Unresolved,
426}
427
428/// Resolves `pkg.mod`, `.mod` and `..mod` against the files of the workspace.
429pub fn resolve(from: &str, spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> Resolution {
430    let try_module = |base: &str| -> Option<usize> {
431        let base = base.trim_matches('/');
432        [format!("{base}.py"), format!("{base}/__init__.py")]
433            .iter()
434            .find_map(|c| index.get(c.as_str()).copied())
435    };
436    if spec.starts_with('.') {
437        let dots = spec.chars().take_while(|c| *c == '.').count();
438        let mut dir: Vec<&str> = from.split('/').collect();
439        dir.pop();
440        for _ in 1..dots {
441            dir.pop();
442        }
443        let rest = spec[dots..].replace('.', "/");
444        let base = if rest.is_empty() {
445            dir.join("/")
446        } else {
447            format!("{}/{rest}", dir.join("/"))
448        };
449        return try_module(&base).map_or(Resolution::Unresolved, Resolution::File);
450    }
451    let path = spec.replace('.', "/");
452    let roots: BTreeSet<&str> = ws
453        .packages
454        .iter()
455        .map(|p| p.src_root.as_str())
456        .chain([""])
457        .collect();
458    for root in roots {
459        let base = if root.is_empty() {
460            path.clone()
461        } else {
462            format!("{root}/{path}")
463        };
464        if let Some(i) = try_module(&base) {
465            return Resolution::File(i);
466        }
467    }
468    let segments: Vec<&str> = spec.split('.').collect();
469    if let Some(known) = (2..=segments.len())
470        .rev()
471        .map(|k| segments[..k].join("."))
472        .find(|name| lookup(name).is_some())
473    {
474        return Resolution::External(known);
475    }
476    let top = segments[0];
477    if STDLIB.contains(&top) {
478        Resolution::Stdlib
479    } else if index
480        .keys()
481        .any(|p| p.starts_with(&format!("{top}/")) || p.contains(&format!("/{top}/")))
482    {
483        // A local package imported by a shorter path than its files: still local.
484        Resolution::Unresolved
485    } else {
486        Resolution::External(top.to_lowercase().replace('_', "-"))
487    }
488}
489
490// The version-agnostic list includes Python 3.12 modules removed in 3.13;
491// imports of their backports can therefore also resolve as stdlib.
492const STDLIB: &[&str] = &[
493    "__future__",
494    "__main__",
495    "_abc",
496    "_aix_support",
497    "_ast",
498    "_asyncio",
499    "_bisect",
500    "_blake2",
501    "_bz2",
502    "_codecs",
503    "_codecs_cn",
504    "_codecs_hk",
505    "_codecs_iso2022",
506    "_codecs_jp",
507    "_codecs_kr",
508    "_codecs_tw",
509    "_collections",
510    "_collections_abc",
511    "_compat_pickle",
512    "_compression",
513    "_contextvars",
514    "_crypt",
515    "_csv",
516    "_ctypes",
517    "_curses",
518    "_curses_panel",
519    "_datetime",
520    "_dbm",
521    "_decimal",
522    "_elementtree",
523    "_frozen_importlib",
524    "_frozen_importlib_external",
525    "_functools",
526    "_gdbm",
527    "_hashlib",
528    "_heapq",
529    "_imp",
530    "_io",
531    "_json",
532    "_locale",
533    "_lsprof",
534    "_lzma",
535    "_markupbase",
536    "_md5",
537    "_msi",
538    "_multibytecodec",
539    "_multiprocessing",
540    "_opcode",
541    "_operator",
542    "_osx_support",
543    "_overlapped",
544    "_pickle",
545    "_posixshmem",
546    "_posixsubprocess",
547    "_py_abc",
548    "_pydatetime",
549    "_pydecimal",
550    "_pyio",
551    "_pylong",
552    "_queue",
553    "_random",
554    "_scproxy",
555    "_sha1",
556    "_sha2",
557    "_sha3",
558    "_signal",
559    "_sitebuiltins",
560    "_socket",
561    "_sqlite3",
562    "_sre",
563    "_ssl",
564    "_stat",
565    "_statistics",
566    "_string",
567    "_strptime",
568    "_struct",
569    "_symtable",
570    "_thread",
571    "_threading_local",
572    "_tkinter",
573    "_tokenize",
574    "_tracemalloc",
575    "_typing",
576    "_uuid",
577    "_warnings",
578    "_weakref",
579    "_weakrefset",
580    "_winapi",
581    "_wmi",
582    "_zoneinfo",
583    "abc",
584    "aifc",
585    "antigravity",
586    "argparse",
587    "array",
588    "ast",
589    "asyncio",
590    "atexit",
591    "audioop",
592    "base64",
593    "bdb",
594    "binascii",
595    "bisect",
596    "builtins",
597    "bz2",
598    "calendar",
599    "cgi",
600    "cgitb",
601    "chunk",
602    "cmath",
603    "cmd",
604    "code",
605    "codecs",
606    "codeop",
607    "collections",
608    "colorsys",
609    "compileall",
610    "concurrent",
611    "configparser",
612    "contextlib",
613    "contextvars",
614    "copy",
615    "copyreg",
616    "cProfile",
617    "crypt",
618    "csv",
619    "ctypes",
620    "curses",
621    "dataclasses",
622    "datetime",
623    "dbm",
624    "decimal",
625    "difflib",
626    "dis",
627    "doctest",
628    "email",
629    "encodings",
630    "ensurepip",
631    "enum",
632    "errno",
633    "faulthandler",
634    "fcntl",
635    "filecmp",
636    "fileinput",
637    "fnmatch",
638    "fractions",
639    "ftplib",
640    "functools",
641    "gc",
642    "genericpath",
643    "getopt",
644    "getpass",
645    "gettext",
646    "glob",
647    "graphlib",
648    "grp",
649    "gzip",
650    "hashlib",
651    "heapq",
652    "hmac",
653    "html",
654    "http",
655    "idlelib",
656    "imaplib",
657    "imghdr",
658    "importlib",
659    "inspect",
660    "io",
661    "ipaddress",
662    "itertools",
663    "json",
664    "keyword",
665    "lib2to3",
666    "linecache",
667    "locale",
668    "logging",
669    "lzma",
670    "mailbox",
671    "mailcap",
672    "marshal",
673    "math",
674    "mimetypes",
675    "mmap",
676    "modulefinder",
677    "msilib",
678    "msvcrt",
679    "multiprocessing",
680    "netrc",
681    "nis",
682    "nntplib",
683    "nt",
684    "ntpath",
685    "nturl2path",
686    "numbers",
687    "opcode",
688    "operator",
689    "optparse",
690    "os",
691    "ossaudiodev",
692    "pathlib",
693    "pdb",
694    "pickle",
695    "pickletools",
696    "pipes",
697    "pkgutil",
698    "platform",
699    "plistlib",
700    "poplib",
701    "posix",
702    "posixpath",
703    "pprint",
704    "profile",
705    "pstats",
706    "pty",
707    "pwd",
708    "py_compile",
709    "pyclbr",
710    "pydoc",
711    "pydoc_data",
712    "pyexpat",
713    "queue",
714    "quopri",
715    "random",
716    "re",
717    "readline",
718    "reprlib",
719    "resource",
720    "rlcompleter",
721    "runpy",
722    "sched",
723    "secrets",
724    "select",
725    "selectors",
726    "shelve",
727    "shlex",
728    "shutil",
729    "signal",
730    "site",
731    "smtplib",
732    "sndhdr",
733    "socket",
734    "socketserver",
735    "spwd",
736    "sqlite3",
737    "sre_compile",
738    "sre_constants",
739    "sre_parse",
740    "ssl",
741    "stat",
742    "statistics",
743    "string",
744    "stringprep",
745    "struct",
746    "subprocess",
747    "sunau",
748    "symtable",
749    "sys",
750    "sysconfig",
751    "syslog",
752    "tabnanny",
753    "tarfile",
754    "telnetlib",
755    "tempfile",
756    "termios",
757    "test",
758    "textwrap",
759    "this",
760    "threading",
761    "time",
762    "timeit",
763    "tkinter",
764    "token",
765    "tokenize",
766    "tomllib",
767    "trace",
768    "traceback",
769    "tracemalloc",
770    "tty",
771    "turtle",
772    "turtledemo",
773    "types",
774    "typing",
775    "typing_extensions",
776    "unicodedata",
777    "unittest",
778    "urllib",
779    "uu",
780    "uuid",
781    "venv",
782    "warnings",
783    "wave",
784    "weakref",
785    "webbrowser",
786    "winreg",
787    "winsound",
788    "wsgiref",
789    "xdrlib",
790    "xml",
791    "xmlrpc",
792    "zipapp",
793    "zipfile",
794    "zipimport",
795    "zlib",
796    "zoneinfo",
797];
798
799// ---- dependencies ----------------------------------------------------------------------------
800
801/// The Rust counterpart of a PyPI package (or import name).
802pub fn lookup(package: &str) -> Option<CrateMatch> {
803    crate::crates::find("python", package)
804}
805
806// ---- exports ---------------------------------------------------------------------------------
807
808/// Decorators that keep a function's behavior as seen by callers.
809const SAFE_DECORATORS: &[&str] = &[
810    "cache",
811    "lru_cache",
812    "functools.cache",
813    "functools.lru_cache",
814    "staticmethod",
815];
816
817/// Public module-level functions and classes, honoring `__all__`.
818pub fn exports(path: &str, source: &str) -> (Vec<ExportedFn>, Vec<ExportedClass>) {
819    let Some(tree) = syntax::parse(&language(), source) else {
820        return (Vec::new(), Vec::new());
821    };
822    let root = tree.root_node();
823    let all = dunder_all(root, source);
824    let public = |name: &str| {
825        all.as_ref().map_or(!name.starts_with('_'), |names| {
826            names.iter().any(|n| n == name)
827        })
828    };
829    let entry = entry_calls(root, source, path.ends_with("__main__.py"));
830    let mut functions = Vec::new();
831    let mut classes = Vec::new();
832    for item in named_children(root) {
833        let (decorators, definition) = unwrap_decorated(item, source);
834        match definition.kind() {
835            "function_definition" => {
836                let Some(mut f) = function(path, definition, source, &decorators, false) else {
837                    continue;
838                };
839                let parser = definition
840                    .child_by_field_name("return_type")
841                    .is_some_and(|t| text(t, source).ends_with("ArgumentParser"));
842                if parser || entry.iter().any(|n| *n == f.name) {
843                    f.blocker = Some(
844                        "a command-line entry point: it stays in Python, and `app front-door` \
845                         takes the command line over when the whole app moves"
846                            .into(),
847                    );
848                }
849                if public(&f.name) {
850                    functions.push(f);
851                }
852            }
853            "class_definition" => {
854                let Some(c) = class(path, definition, source, &decorators) else {
855                    continue;
856                };
857                if public(&c.name) {
858                    classes.push(c);
859                }
860            }
861            _ => {}
862        }
863    }
864    (functions, classes)
865}
866
867/// Dataclasses declared at the top level of a file, as types `record` can build values of:
868/// `{ $object: "Name"; attrs: { field: type; defaulted?: type } }`, which the Python driver
869/// turns into an instance of the class.
870pub fn dataclass_types(source: &str) -> Vec<crate::ts::exports::LocalType> {
871    let Some(tree) = syntax::parse(&language(), source) else {
872        return Vec::new();
873    };
874    let mut out = Vec::new();
875    for item in named_children(tree.root_node()) {
876        let (decorators, definition) = unwrap_decorated(item, source);
877        if definition.kind() != "class_definition"
878            || !decorators.iter().any(|d| d.contains("dataclass"))
879        {
880            continue;
881        }
882        let Some(name) = definition.child_by_field_name("name") else {
883            continue;
884        };
885        let mut fields = Vec::new();
886        if let Some(body) = definition.child_by_field_name("body") {
887            for statement in named_children(body) {
888                let Some(assignment) = named_children(statement)
889                    .into_iter()
890                    .find(|n| n.kind() == "assignment")
891                else {
892                    continue;
893                };
894                let (Some(left), Some(ty)) = (
895                    assignment.child_by_field_name("left"),
896                    assignment.child_by_field_name("type"),
897                ) else {
898                    continue;
899                };
900                let hint = text(ty, source);
901                if hint.starts_with("ClassVar") || hint.starts_with("typing.ClassVar") {
902                    continue;
903                }
904                let optional = if assignment.child_by_field_name("right").is_some() {
905                    "?"
906                } else {
907                    ""
908                };
909                fields.push(format!(
910                    "{}{optional}: {}",
911                    text(left, source),
912                    to_ts_type(hint)
913                ));
914            }
915        }
916        let name = text(name, source).to_string();
917        out.push(crate::ts::exports::LocalType {
918            text: format!(
919                "{{ $object: {name:?}; attrs: {{ {} }} }}",
920                fields.join("; ")
921            ),
922            name,
923            alias: true,
924        });
925    }
926    out
927}
928
929/// Functions the file runs as a program: the calls inside `if __name__ == "__main__":`, or
930/// every top-level call in a package's `__main__.py`.
931fn entry_calls<'s>(root: Node, source: &'s str, main_module: bool) -> Vec<&'s str> {
932    let mut out = Vec::new();
933    let mut collect = |node: Node| {
934        syntax::walk(node, |n| {
935            if n.kind() == "call"
936                && let Some(f) = n.child_by_field_name("function")
937                && f.kind() == "identifier"
938            {
939                out.push(text(f, source));
940            }
941        });
942    };
943    for statement in named_children(root) {
944        let guard = statement.kind() == "if_statement"
945            && statement.child_by_field_name("condition").is_some_and(|c| {
946                let c = text(c, source).replace(' ', "").replace('\'', "\"");
947                c == "__name__==\"__main__\"" || c == "\"__main__\"==__name__"
948            });
949        if guard {
950            if let Some(body) = statement.child_by_field_name("consequence") {
951                collect(body);
952            }
953        } else if main_module && statement.kind() == "expression_statement" {
954            collect(statement);
955        }
956    }
957    out
958}
959
960/// The names a module's `__all__` lists, when its top level sets it from string literals only:
961/// `__all__ = [...]` (with or without a type; the last one wins) and `__all__ += [...]`. `None`
962/// when there is no `__all__`, or when it is built or changed any other way (`+ other.__all__`,
963/// `sorted(...)`, `__all__.extend(...)`, inside an `if` or `try` block), so the caller falls
964/// back to the names without a leading underscore instead of trusting a partial list.
965fn dunder_all(root: Node, source: &str) -> Option<Vec<String>> {
966    let mut names: Option<Vec<String>> = None;
967    for statement in named_children(root) {
968        match statement.kind() {
969            "expression_statement" => {}
970            // Their bodies are not the module's top level.
971            "function_definition" | "class_definition" | "decorated_definition" => continue,
972            // A change inside a block (`if sys.platform == ...: __all__ += [...]`) cannot be
973            // followed.
974            _ if mentions_all(statement, source) => return None,
975            _ => continue,
976        }
977        for node in named_children(statement) {
978            let left = node.child_by_field_name("left").map(|l| text(l, source));
979            match node.kind() {
980                "assignment" | "augmented_assignment" if left == Some("__all__") => {
981                    // `__all__: list[str]` alone declares it without a value.
982                    let Some(right) = node.child_by_field_name("right") else {
983                        continue;
984                    };
985                    let listed = string_literals(right, source)?;
986                    match node
987                        .child_by_field_name("operator")
988                        .map(|o| text(o, source))
989                    {
990                        None => names = Some(listed),
991                        Some("+=") => names.get_or_insert_with(Vec::new).extend(listed),
992                        Some(_) => return None,
993                    }
994                }
995                _ if mentions_all(node, source) => return None,
996                _ => {}
997            }
998        }
999    }
1000    names
1001}
1002
1003/// The values of a list or tuple made only of plain string literals (comments allowed).
1004fn string_literals(node: Node, source: &str) -> Option<Vec<String>> {
1005    if !matches!(node.kind(), "list" | "tuple" | "expression_list") {
1006        return None;
1007    }
1008    let mut out = Vec::new();
1009    for item in named_children(node) {
1010        match item.kind() {
1011            "comment" => {}
1012            "string" => {
1013                let mut content = String::new();
1014                for part in named_children(item) {
1015                    match part.kind() {
1016                        // Bytes are not names.
1017                        "string_start" if text(part, source).contains(['b', 'B']) => return None,
1018                        "string_start" | "string_end" => {}
1019                        // Escape sequences would need decoding.
1020                        "string_content" if part.named_child_count() > 0 => return None,
1021                        "string_content" => content.push_str(text(part, source)),
1022                        _ => return None,
1023                    }
1024                }
1025                out.push(content);
1026            }
1027            _ => return None,
1028        }
1029    }
1030    Some(out)
1031}
1032
1033/// Whether the module's own `__all__` appears inside `node`; `other.__all__` and a keyword
1034/// argument named `__all__` do not count.
1035fn mentions_all(node: Node, source: &str) -> bool {
1036    match node.kind() {
1037        "identifier" => text(node, source) == "__all__",
1038        "attribute" => node
1039            .child_by_field_name("object")
1040            .is_some_and(|object| mentions_all(object, source)),
1041        "keyword_argument" => node
1042            .child_by_field_name("value")
1043            .is_some_and(|value| mentions_all(value, source)),
1044        _ => named_children(node)
1045            .into_iter()
1046            .any(|child| mentions_all(child, source)),
1047    }
1048}
1049
1050fn unwrap_decorated<'t>(node: Node<'t>, source: &str) -> (Vec<String>, Node<'t>) {
1051    if node.kind() != "decorated_definition" {
1052        return (Vec::new(), node);
1053    }
1054    let decorators = named_children(node)
1055        .into_iter()
1056        .filter(|n| n.kind() == "decorator")
1057        .map(|d| {
1058            let t = text(d, source).trim_start_matches('@').trim();
1059            t.split('(').next().unwrap_or(t).to_string()
1060        })
1061        .collect();
1062    (
1063        decorators,
1064        node.child_by_field_name("definition").unwrap_or(node),
1065    )
1066}
1067
1068/// Unannotated parameters the body uses as numbers (`r - g`, `x * 0.5`, `max(r, g)`, `x < 1`)
1069/// become `number`: generated inputs then fit what the code expects.
1070pub fn infer_numbers(params: &mut [Param], body: Node, source: &str) {
1071    let unknown: Vec<String> = params
1072        .iter()
1073        .filter(|p| p.ts_type == "unknown" && p.default.is_none())
1074        .map(|p| p.name.clone())
1075        .collect();
1076    if unknown.is_empty() {
1077        return;
1078    }
1079    let mut numeric: Vec<String> = Vec::new();
1080    let is_number = |n: Node| matches!(n.kind(), "integer" | "float");
1081    syntax::walk(body, |n| {
1082        let operands: Vec<Node> = match n.kind() {
1083            "binary_operator" => {
1084                let op = n
1085                    .child_by_field_name("operator")
1086                    .map_or("", |o| text(o, source));
1087                let (Some(l), Some(r)) = (
1088                    n.child_by_field_name("left"),
1089                    n.child_by_field_name("right"),
1090                ) else {
1091                    return;
1092                };
1093                match op {
1094                    "-" | "*" | "/" | "//" | "**" => vec![l, r],
1095                    "+" | "%" if is_number(l) || is_number(r) => vec![l, r],
1096                    _ => return,
1097                }
1098            }
1099            "comparison_operator" => {
1100                let parts = named_children(n);
1101                if !parts.iter().any(|p| is_number(*p)) {
1102                    return;
1103                }
1104                parts
1105            }
1106            "call" => {
1107                let f = n
1108                    .child_by_field_name("function")
1109                    .map_or("", |f| text(f, source));
1110                if !matches!(
1111                    f,
1112                    "min" | "max" | "abs" | "round" | "float" | "int" | "divmod"
1113                ) && !f.starts_with("math.")
1114                {
1115                    return;
1116                }
1117                n.child_by_field_name("arguments")
1118                    .map(named_children)
1119                    .unwrap_or_default()
1120            }
1121            _ => return,
1122        };
1123        for o in operands {
1124            if o.kind() == "identifier" {
1125                let name = text(o, source).to_string();
1126                if unknown.contains(&name) && !numeric.contains(&name) {
1127                    numeric.push(name);
1128                }
1129            }
1130        }
1131    });
1132    for p in params.iter_mut().filter(|p| numeric.contains(&p.name)) {
1133        p.ts_type = "number".into();
1134    }
1135}
1136
1137fn function(
1138    path: &str,
1139    node: Node,
1140    source: &str,
1141    decorators: &[String],
1142    method: bool,
1143) -> Option<ExportedFn> {
1144    let name = text(node.child_by_field_name("name")?, source).to_string();
1145    let (mut params, mut blocker) =
1146        parameters(node.child_by_field_name("parameters")?, source, method);
1147    let body = node.child_by_field_name("body");
1148    if let Some(body) = body {
1149        infer_numbers(&mut params, body, source);
1150    }
1151    let mut generator = false;
1152    if let Some(body) = body {
1153        syntax::walk(body, |n| {
1154            if n.kind() == "yield" {
1155                generator = true;
1156            }
1157        });
1158    }
1159    // An untyped parameter that the body calls is a callable: it cannot cross a bridge.
1160    if let Some(body) = body {
1161        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
1162        syntax::walk(body, |n| {
1163            if n.kind() == "call"
1164                && let Some(f) = n.child_by_field_name("function")
1165                && f.kind() == "identifier"
1166                && names.contains(&text(f, source))
1167                && blocker.is_none()
1168            {
1169                blocker = Some(format!(
1170                    "calls its parameter `{}`: a callable",
1171                    text(f, source)
1172                ));
1173            }
1174        });
1175    }
1176    if let Some(d) = decorators
1177        .iter()
1178        .find(|d| !SAFE_DECORATORS.contains(&d.as_str()))
1179    {
1180        blocker = blocker.or_else(|| Some(format!("decorated with `@{d}`")));
1181    }
1182    Some(ExportedFn {
1183        name,
1184        file: path.to_string(),
1185        line: syntax::line(node),
1186        params,
1187        returns: node
1188            .child_by_field_name("return_type")
1189            .map_or_else(|| "unknown".into(), |r| to_ts_type(text(r, source))),
1190        is_async: text(node, source).starts_with("async"),
1191        is_generator: generator,
1192        blocker,
1193        ..Default::default()
1194    })
1195}
1196
1197/// Parameters in the type dialect, and a reason when the signature cannot cross a bridge.
1198fn parameters(node: Node, source: &str, method: bool) -> (Vec<Param>, Option<String>) {
1199    let mut params = Vec::new();
1200    let mut blocker = None;
1201    let mut keyword_only = false;
1202    for (i, p) in named_children(node).into_iter().enumerate() {
1203        let name = |n: Option<Node>| n.map(|n| text(n, source).to_string()).unwrap_or_default();
1204        let param = match p.kind() {
1205            "identifier" => Param {
1206                name: text(p, source).into(),
1207                ts_type: "unknown".into(),
1208                ..Default::default()
1209            },
1210            "typed_parameter" => {
1211                let inner = named_children(p).into_iter().next();
1212                let ty = p
1213                    .child_by_field_name("type")
1214                    .map_or_else(|| "unknown".into(), |t| to_ts_type(text(t, source)));
1215                match inner.map(|n| n.kind()) {
1216                    Some("list_splat_pattern") => {
1217                        blocker = Some("takes `*args`".into());
1218                        continue;
1219                    }
1220                    Some("dictionary_splat_pattern") => {
1221                        blocker = Some("takes `**kwargs`".into());
1222                        continue;
1223                    }
1224                    _ => Param {
1225                        name: name(inner),
1226                        ts_type: ty,
1227                        ..Default::default()
1228                    },
1229                }
1230            }
1231            "default_parameter" | "typed_default_parameter" => {
1232                let value = p.child_by_field_name("value");
1233                let default = value.map(|v| text(v, source).to_string());
1234                let ty = match p.child_by_field_name("type") {
1235                    Some(t) => to_ts_type(text(t, source)),
1236                    None => match value.map(|v| v.kind()) {
1237                        Some("integer") => "int".into(),
1238                        Some("float") => "number".into(),
1239                        Some("string") => "string".into(),
1240                        Some("true" | "false") => "boolean".into(),
1241                        _ => "unknown".into(),
1242                    },
1243                };
1244                Param {
1245                    name: name(p.child_by_field_name("name")),
1246                    ts_type: ty,
1247                    optional: true,
1248                    default,
1249                    ..Default::default()
1250                }
1251            }
1252            "list_splat_pattern" => {
1253                blocker = Some("takes `*args`".into());
1254                continue;
1255            }
1256            "dictionary_splat_pattern" => {
1257                blocker = Some("takes `**kwargs`".into());
1258                continue;
1259            }
1260            "keyword_separator" => {
1261                keyword_only = true;
1262                continue;
1263            }
1264            _ => continue,
1265        };
1266        if method && i == 0 && (param.name == "self" || param.name == "cls") {
1267            continue;
1268        }
1269        params.push(Param {
1270            keyword_only,
1271            ..param
1272        });
1273    }
1274    (params, blocker)
1275}
1276
1277fn class(path: &str, node: Node, source: &str, decorators: &[String]) -> Option<ExportedClass> {
1278    let name = text(node.child_by_field_name("name")?, source).to_string();
1279    let mut blockers = Vec::new();
1280    if let Some(bases) = node.child_by_field_name("superclasses") {
1281        let bases: Vec<&str> = named_children(bases)
1282            .into_iter()
1283            .map(|b| text(b, source))
1284            .filter(|b| *b != "object")
1285            .collect();
1286        if !bases.is_empty() {
1287            blockers.push(format!("inherits from {}", bases.join(", ")));
1288        }
1289    }
1290    if let Some(d) = decorators.first() {
1291        blockers.push(format!("decorated with `@{d}`"));
1292    }
1293    let mut constructor = Vec::new();
1294    let mut methods = Vec::new();
1295    for item in named_children(node.child_by_field_name("body")?) {
1296        let (decorators, definition) = unwrap_decorated(item, source);
1297        match definition.kind() {
1298            "function_definition" => {
1299                let method_name = definition
1300                    .child_by_field_name("name")
1301                    .map_or("", |n| text(n, source));
1302                if method_name == "__init__" {
1303                    let (params, blocker) =
1304                        parameters(definition.child_by_field_name("parameters")?, source, true);
1305                    constructor = params;
1306                    blockers.extend(blocker);
1307                    // `self.name = ...` with a public name: callers can read the attribute.
1308                    if let Some(body) = definition.child_by_field_name("body") {
1309                        syntax::walk(body, |n| {
1310                            if n.kind() == "assignment"
1311                                && let Some(left) = n.child_by_field_name("left")
1312                                && let Some(attr) = text(left, source).strip_prefix("self.")
1313                                && !attr.starts_with('_')
1314                                && !attr.contains('.')
1315                            {
1316                                blockers.push(format!("public attribute `{attr}`"));
1317                            }
1318                        });
1319                    }
1320                } else if method_name.starts_with("__") && method_name.ends_with("__") {
1321                    blockers.push(format!("special method `{method_name}`"));
1322                } else if method_name.starts_with('_') {
1323                } else if let Some(d) = decorators.first() {
1324                    blockers.push(format!("`@{d}` method `{method_name}`"));
1325                } else if let Some(f) = function(path, definition, source, &[], true) {
1326                    if f.is_async || f.is_generator {
1327                        blockers.push(format!("async or generator method `{}`", f.name));
1328                    }
1329                    if f.returns
1330                        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
1331                        .any(|w| w == name || w == "Self")
1332                    {
1333                        blockers.push(format!("method `{}` returns an instance", f.name));
1334                    }
1335                    methods.push(f);
1336                }
1337            }
1338            "expression_statement" => {
1339                let assignment = named_children(definition)
1340                    .into_iter()
1341                    .find(|n| n.kind() == "assignment");
1342                if let Some(left) = assignment.and_then(|a| a.child_by_field_name("left")) {
1343                    let attr = text(left, source);
1344                    if !attr.starts_with('_') {
1345                        blockers.push(format!("public class attribute `{attr}`"));
1346                    }
1347                }
1348            }
1349            _ => {}
1350        }
1351    }
1352    blockers.sort();
1353    blockers.dedup();
1354    Some(ExportedClass {
1355        name,
1356        file: path.to_string(),
1357        line: syntax::line(node),
1358        constructor,
1359        methods,
1360        blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
1361    })
1362}
1363
1364/// A Python type hint in the TS-like dialect: `list[str]` -> `string[]`, `Optional[int]` ->
1365/// `int | undefined`, `Callable[...]` -> a function type (which keeps the export in Python).
1366pub fn to_ts_type(hint: &str) -> String {
1367    let hint = hint.trim().trim_matches(|c| c == '"' || c == '\'');
1368    let hint = hint.strip_prefix("typing.").unwrap_or(hint);
1369    let top = split_top(hint, '|');
1370    if top.len() > 1 {
1371        return top
1372            .iter()
1373            .map(|p| to_ts_type(p))
1374            .collect::<Vec<_>>()
1375            .join(" | ");
1376    }
1377    let (head, args) = match hint.find('[') {
1378        Some(i) if hint.ends_with(']') => {
1379            (&hint[..i], split_top(&hint[i + 1..hint.len() - 1], ','))
1380        }
1381        _ => (hint, Vec::new()),
1382    };
1383    let head = head.trim().strip_prefix("typing.").unwrap_or(head.trim());
1384    let arg = |i: usize| {
1385        args.get(i)
1386            .map_or_else(|| "unknown".to_string(), |a| to_ts_type(a))
1387    };
1388    match head {
1389        "str" => "string".into(),
1390        "int" => "int".into(),
1391        "float" => "number".into(),
1392        "bool" => "boolean".into(),
1393        "bytes" | "bytearray" | "memoryview" => "pybytes".into(),
1394        "None" | "NoneType" => "undefined".into(),
1395        "list" | "List" | "Sequence" | "Iterable" | "MutableSequence" | "Collection" => {
1396            format!("{}[]", wrap(&arg(0)))
1397        }
1398        "Optional" => format!("{} | undefined", arg(0)),
1399        "Union" => args
1400            .iter()
1401            .map(|a| to_ts_type(a))
1402            .collect::<Vec<_>>()
1403            .join(" | "),
1404        "dict" | "Dict" | "Mapping" | "MutableMapping" if arg(0) == "string" => {
1405            format!("Record<string, {}>", arg(1))
1406        }
1407        "Literal" => args
1408            .iter()
1409            .map(|a| a.trim().replace('"', "'"))
1410            .collect::<Vec<_>>()
1411            .join(" | "),
1412        "Callable" => "(...args: unknown[]) => unknown".into(),
1413        "Any" | "object" => "unknown".into(),
1414        // Tuples, sets, other dicts and named classes cross as JSON.
1415        other => other.to_string(),
1416    }
1417}
1418
1419fn wrap(ts: &str) -> String {
1420    if ts.contains('|') {
1421        format!("({ts})")
1422    } else {
1423        ts.to_string()
1424    }
1425}
1426
1427fn split_top(text: &str, sep: char) -> Vec<String> {
1428    let mut out = Vec::new();
1429    let mut depth = 0i32;
1430    let mut current = String::new();
1431    for c in text.chars() {
1432        match c {
1433            '[' | '(' => depth += 1,
1434            ']' | ')' => depth -= 1,
1435            _ => {}
1436        }
1437        if c == sep && depth == 0 {
1438            out.push(current.trim().to_string());
1439            current.clear();
1440        } else {
1441            current.push(c);
1442        }
1443    }
1444    if !current.trim().is_empty() {
1445        out.push(current.trim().to_string());
1446    }
1447    out
1448}
1449
1450#[cfg(test)]
1451mod tests {
1452    use super::*;
1453
1454    #[test]
1455    fn maps_type_hints() {
1456        assert_eq!(to_ts_type("list[str]"), "string[]");
1457        assert_eq!(to_ts_type("Optional[int]"), "int | undefined");
1458        assert_eq!(to_ts_type("str | None"), "string | undefined");
1459        assert_eq!(
1460            to_ts_type("dict[str, list[float]]"),
1461            "Record<string, number[]>"
1462        );
1463        assert_eq!(to_ts_type("Literal['a', \"b\"]"), "'a' | 'b'");
1464        assert!(to_ts_type("Callable[[int], str]").contains("=>"));
1465        assert_eq!(to_ts_type("tuple[int, int]"), "tuple");
1466    }
1467
1468    #[test]
1469    fn unix_stdlib_is_not_external() {
1470        // `import fcntl` in a pure-Python package must not surface as an unknown
1471        // (npm) dependency: it is Unix stdlib with no PyPI counterpart to look up.
1472        for module in [
1473            "fcntl", "termios", "resource", "grp", "pwd", "posix", "syslog",
1474        ] {
1475            assert!(
1476                STDLIB.contains(&module),
1477                "{module} should resolve as stdlib"
1478            );
1479        }
1480    }
1481
1482    #[test]
1483    fn standard_library_imports_resolve_without_dependencies() {
1484        let ws = Workspace {
1485            packages: vec![],
1486            files: vec![],
1487        };
1488        let index = HashMap::new();
1489        for module in [
1490            "faulthandler",
1491            "site",
1492            "bdb",
1493            "graphlib",
1494            "_thread",
1495            "telnetlib",
1496            "cgi",
1497        ] {
1498            assert!(
1499                matches!(resolve("main.py", module, &index, &ws), Resolution::Stdlib),
1500                "{module}"
1501            );
1502        }
1503        assert!(matches!(
1504            resolve("main.py", "requests", &index, &ws),
1505            Resolution::External(_)
1506        ));
1507        let local = HashMap::from([("site.py", 0)]);
1508        assert!(matches!(
1509            resolve("main.py", "site", &local, &ws),
1510            Resolution::File(0)
1511        ));
1512    }
1513
1514    #[test]
1515    fn a_dotted_import_the_table_knows_keeps_its_dotted_name() {
1516        let ws = Workspace {
1517            packages: vec![],
1518            files: vec![],
1519        };
1520        let index = HashMap::new();
1521        for spec in ["google.protobuf", "google.protobuf.json_format"] {
1522            match resolve("main.py", spec, &index, &ws) {
1523                Resolution::External(name) => assert_eq!(name, "google.protobuf", "{spec}"),
1524                _ => panic!("{spec}: not external"),
1525            }
1526        }
1527        match resolve("main.py", "yaml.loader", &index, &ws) {
1528            Resolution::External(name) => assert_eq!(name, "yaml"),
1529            _ => panic!("yaml.loader: not external"),
1530        }
1531    }
1532
1533    #[test]
1534    fn reads_exports() {
1535        let source = "__all__ = ['slug', 'Counter']\n\n\
1536            def slug(text: str, sep: str = '-', *, lower=True) -> str:\n    return text\n\n\
1537            def hidden(x): pass\n\n\
1538            @lru_cache\ndef cached(n: int) -> int:\n    return n\n\n\
1539            def gen(n: int):\n    yield n\n\n\
1540            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\
1541            class Point:\n    def __init__(self, x):\n        self.x = x\n";
1542        let (functions, classes) = exports("m.py", source);
1543        assert_eq!(
1544            functions
1545                .iter()
1546                .map(|f| f.name.as_str())
1547                .collect::<Vec<_>>(),
1548            ["slug"]
1549        );
1550        let slug = &functions[0];
1551        assert_eq!(slug.params[1].default.as_deref(), Some("'-'"));
1552        assert!(slug.params[2].keyword_only && slug.params[2].ts_type == "boolean");
1553        assert_eq!(slug.returns, "string");
1554        assert_eq!(classes.len(), 1);
1555        assert!(classes[0].blocker.is_none());
1556        assert_eq!(classes[0].methods.len(), 1);
1557
1558        let (all, classes) = exports(
1559            "n.py",
1560            &source.replace("__all__ = ['slug', 'Counter']\n", ""),
1561        );
1562        let names: Vec<&str> = all.iter().map(|f| f.name.as_str()).collect();
1563        assert_eq!(names, ["slug", "hidden", "cached", "gen"]);
1564        assert!(all[3].is_generator);
1565        assert!(
1566            classes[1]
1567                .blocker
1568                .as_deref()
1569                .unwrap()
1570                .contains("public attribute `x`")
1571        );
1572    }
1573
1574    #[test]
1575    fn reads_all_after_a_docstring_and_imports() {
1576        let source = "\"\"\"Text helpers.\"\"\"\n\
1577            from os import path\n\
1578            import re\n\n\
1579            __all__ = ['slug', '_kept']\n\n\
1580            def slug(text: str) -> str:\n    return text\n\n\
1581            def helper(x: int) -> int:\n    return x\n\n\
1582            def _kept(x: int) -> int:\n    return x\n";
1583        let (functions, _) = exports("m.py", source);
1584        let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
1585        assert_eq!(names, ["slug", "_kept"]);
1586    }
1587
1588    fn exported(source: &str) -> Vec<String> {
1589        let defs = "\ndef a(x: int) -> int:\n    return x\n\n\
1590            def b(x: int) -> int:\n    return x\n\n\
1591            def _c(x: int) -> int:\n    return x\n";
1592        exports("m.py", &format!("{source}{defs}"))
1593            .0
1594            .into_iter()
1595            .map(|f| f.name)
1596            .collect()
1597    }
1598
1599    #[test]
1600    fn later_changes_to_all_are_followed() {
1601        assert_eq!(
1602            exported("__all__ = ['a']\n__all__ += ['_c']\n"),
1603            ["a", "_c"]
1604        );
1605        assert_eq!(exported("__all__ = ['a']\n__all__ = ['b']\n"), ["b"]);
1606    }
1607
1608    #[test]
1609    fn annotated_prefixed_and_commented_all_is_read() {
1610        let source =
1611            "__all__: list[str]\n__all__: list[str] = [\n    r'a',  # first\n    \"_c\",\n]\n";
1612        assert_eq!(exported(source), ["a", "_c"]);
1613    }
1614
1615    #[test]
1616    fn an_all_built_any_other_way_falls_back_to_public_names() {
1617        for source in [
1618            "import other\n__all__ = ['a'] + other.__all__\n",
1619            "__all__ = sorted(['a'])\n",
1620            "__all__ = ['a']\n__all__.extend(['_c'])\n",
1621            "__all__ = [f'{1}']\n",
1622            "import sys\n__all__ = ['a']\nif sys.platform == 'win32':\n    __all__ += ['_c']\n",
1623            "__all__ = ['\\x61']\n",
1624            "__all__ = [b'a']\n",
1625        ] {
1626            assert_eq!(exported(source), ["a", "b"], "{source}");
1627        }
1628    }
1629
1630    #[test]
1631    fn another_module_all_and_reads_in_functions_keep_the_list() {
1632        let source = "import other\n__all__ = ['a']\nnames = other.__all__\n\n\
1633            def __dir__():\n    return __all__\n";
1634        assert_eq!(exported(source), ["a"]);
1635    }
1636
1637    #[test]
1638    fn scans_risks_and_imports() {
1639        let facts = scan(
1640            "import os\nfrom .util import helper\nimport re\nx = 7 // 2\nx &= 0xff\nx |= 1\nx ^= 2\nx >>= 1\nre.compile(r'(?<=a)b')\nfor i in range(3): pass\n",
1641        );
1642        let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1643        assert!(
1644            specs.contains(&"os") && specs.contains(&".util") && specs.contains(&".util.helper")
1645        );
1646        assert!(facts.risks.contains_key(&Risk::DivisionSemantics));
1647        assert_eq!(
1648            facts.risks.get(&Risk::NumberSemantics).map(Vec::as_slice),
1649            Some(&[5, 6, 7, 8][..])
1650        );
1651        assert!(facts.risks.contains_key(&Risk::RegexSyntax));
1652        assert_eq!(facts.loops, 1);
1653    }
1654
1655    #[test]
1656    fn infers_numbers_from_arithmetic() {
1657        let src = "def rgb_to_hsv(r, g, b):\n    maxc = max(r, g, b)\n    return maxc - r\n\n\
1658                   def greet(name):\n    return 'hi ' + name\n";
1659        let (fns, _) = exports("colorsys.py", src);
1660        let types: Vec<&str> = fns[0].params.iter().map(|p| p.ts_type.as_str()).collect();
1661        assert_eq!(types, ["number", "number", "number"]);
1662        assert_eq!(fns[1].params[0].ts_type, "unknown");
1663    }
1664
1665    #[test]
1666    fn maps_bytes_hints_to_bytes_dialect_type() {
1667        assert_eq!(to_ts_type("bytes"), "pybytes");
1668        assert_eq!(to_ts_type("bytearray"), "pybytes");
1669        assert_eq!(to_ts_type("memoryview"), "pybytes");
1670        assert_eq!(to_ts_type("Optional[bytes]"), "pybytes | undefined");
1671        assert_eq!(to_ts_type("list[bytes]"), "pybytes[]");
1672        assert_eq!(to_ts_type("bytes | None"), "pybytes | undefined");
1673    }
1674}