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