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