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