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, Fit};
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 = ignore::WalkBuilder::new(root)
44 .hidden(true)
45 .require_git(false)
46 .filter_entry(|e| {
47 !(e.file_type().is_some_and(|t| t.is_dir())
48 && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
49 })
50 .build();
51 for entry in walker.flatten() {
52 if !entry.file_type().is_some_and(|t| t.is_file()) {
53 continue;
54 }
55 let Ok(rel) = entry.path().strip_prefix(root) else {
56 continue;
57 };
58 let rel = rel.to_string_lossy().replace('\\', "/");
59 let name = rel.rsplit('/').next().unwrap_or(&rel);
60 if matches!(name, "pyproject.toml" | "setup.py" | "setup.cfg") {
61 let dir = rel
62 .rsplit_once('/')
63 .map_or(String::new(), |(d, _)| d.to_string());
64 if !manifests.contains(&dir) {
65 manifests.push(dir);
66 }
67 } else if name.ends_with(".py") && name != "setup.py" && name != "conftest.py" {
68 let is_test = name.starts_with("test_")
69 || name.ends_with("_test.py")
70 || rel
71 .split('/')
72 .any(|p| matches!(p, "tests" | "test" | "testing"));
73 files.push((
74 rel,
75 if is_test {
76 FileKind::Test
77 } else {
78 FileKind::Source
79 },
80 ));
81 }
82 }
83 let mut packages: Vec<Package> = manifests
84 .iter()
85 .map(|dir| read_package(root, dir))
86 .collect();
87 if !packages.iter().any(|p| p.dir.is_empty()) {
88 packages.push(Package {
89 name: root
90 .file_name()
91 .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
92 dir: String::new(),
93 src_root: if root.join("src").is_dir() {
94 "src".into()
95 } else {
96 String::new()
97 },
98 deps: Vec::new(),
99 dev_deps: Vec::new(),
100 });
101 }
102 packages.sort_by(|a, b| a.dir.cmp(&b.dir));
103 files.sort_by(|a, b| a.0.cmp(&b.0));
104 let files = files
105 .into_iter()
106 .map(|(path, kind)| {
107 let package = packages
108 .iter()
109 .enumerate()
110 .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
111 .max_by_key(|(_, p)| p.dir.len())
112 .map_or(0, |(i, _)| i);
113 SourceFile {
114 path,
115 package,
116 kind,
117 }
118 })
119 .collect();
120 Ok(Workspace { packages, files })
121}
122
123fn read_package(root: &Path, dir: &str) -> Package {
124 let join = |name: &str| {
125 if dir.is_empty() {
126 name.to_string()
127 } else {
128 format!("{dir}/{name}")
129 }
130 };
131 let mut name = None;
132 let mut deps = Vec::new();
133 if let Ok(text) = std::fs::read_to_string(root.join(join("pyproject.toml")))
134 && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
135 {
136 name = doc
137 .get("project")
138 .and_then(|p| p.get("name"))
139 .and_then(|n| n.as_str())
140 .map(str::to_string);
141 if let Some(list) = doc
142 .get("project")
143 .and_then(|p| p.get("dependencies"))
144 .and_then(|d| d.as_array())
145 {
146 deps.extend(list.iter().filter_map(|d| d.as_str()).map(requirement_name));
147 }
148 }
149 if let Ok(text) = std::fs::read_to_string(root.join(join("requirements.txt"))) {
150 deps.extend(
151 text.lines()
152 .map(str::trim)
153 .filter(|l| !l.is_empty() && !l.starts_with('#'))
154 .map(requirement_name),
155 );
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 }
176}
177
178fn requirement_name(line: &str) -> String {
180 line.split(|c: char| !(c.is_alphanumeric() || c == '-' || c == '_' || c == '.'))
181 .next()
182 .unwrap_or("")
183 .to_lowercase()
184 .replace('_', "-")
185}
186
187pub fn scan(source: &str) -> FileFacts {
190 let mut facts = FileFacts {
191 loc: syntax::loc(source),
192 ..FileFacts::default()
193 };
194 let Some(tree) = syntax::parse(&language(), source) else {
195 return facts;
196 };
197 let root = tree.root_node();
198 facts.parse_errors = usize::from(root.has_error());
199 let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
200 facts
201 .risks
202 .entry(risk)
203 .or_default()
204 .push(syntax::line(node));
205 };
206 syntax::walk(root, |node| match node.kind() {
207 "import_statement" => {
208 for child in named_children(node) {
209 let name = child.child_by_field_name("name").unwrap_or(child);
210 facts.imports.push(Import {
211 specifier: text(name, source).to_string(),
212 type_only: false,
213 dynamic: false,
214 });
215 }
216 }
217 "import_from_statement" => {
218 let Some(module) = node.child_by_field_name("module_name") else {
219 return;
220 };
221 let module = text(module, source).to_string();
222 facts.imports.push(Import {
223 specifier: module.clone(),
224 type_only: false,
225 dynamic: false,
226 });
227 let mut cursor = node.walk();
229 for name in node.children_by_field_name("name", &mut cursor) {
230 let name = name.child_by_field_name("name").unwrap_or(name);
231 let sep = if module.ends_with('.') { "" } else { "." };
232 facts.imports.push(Import {
233 specifier: format!("{module}{sep}{}", text(name, source)),
234 type_only: true,
235 dynamic: false,
236 });
237 }
238 }
239 "call" => {
240 let Some(function) = node.child_by_field_name("function") else {
241 return;
242 };
243 let callee = text(function, source);
244 match callee {
245 "eval" | "exec" | "compile" | "__import__" | "importlib.import_module" => {
246 add(&mut facts, Risk::DynamicCode, node)
247 }
248 "getattr" | "setattr" | "hasattr" | "delattr" | "isinstance" | "type" => {
249 add(&mut facts, Risk::DynamicTyping, node);
250 }
251 "globals" | "locals" | "vars" => add(&mut facts, Risk::Reflection, node),
252 "set" | "frozenset" => add(&mut facts, Risk::UnorderedIteration, node),
253 "threading.Thread"
254 | "Thread"
255 | "ThreadPoolExecutor"
256 | "ProcessPoolExecutor"
257 | "asyncio.gather" => {
258 add(&mut facts, Risk::Concurrency, node);
259 }
260 _ if callee.starts_with("re.") => {
261 let pattern = node
262 .child_by_field_name("arguments")
263 .and_then(|a| named_children(a).into_iter().next())
264 .filter(|a| a.kind() == "string");
265 match pattern {
266 Some(p) if regex_needs_fancy(text(p, source), "") => {
267 add(&mut facts, Risk::RegexSyntax, node)
268 }
269 Some(_) => {}
270 None => add(&mut facts, Risk::DynamicRegex, node),
271 }
272 }
273 _ if callee.ends_with(".find")
274 || callee.ends_with(".index")
275 || callee.ends_with(".rfind") =>
276 {
277 add(&mut facts, Risk::StringOffsets, node);
278 }
279 _ => {}
280 }
281 }
282 "subscript" if named_children(node).iter().any(|c| c.kind() == "slice") => {
283 add(&mut facts, Risk::StringOffsets, node)
284 }
285 "binary_operator" | "augmented_assignment" => {
286 let op = node
287 .child_by_field_name("operator")
288 .map_or("", |o| text(o, source));
289 match op {
290 "//" | "%" | "//=" | "%=" => add(&mut facts, Risk::DivisionSemantics, node),
291 "**" | "**=" | "<<" | "<<=" => add(&mut facts, Risk::IntegerSemantics, node),
292 "&" | "|" | "^" | ">>" => add(&mut facts, Risk::NumberSemantics, node),
293 _ => {}
294 }
295 }
296 "set" | "set_comprehension" => add(&mut facts, Risk::UnorderedIteration, node),
297 "decorator" if crate::risks::compiled_by(text(node, source)).is_some() => {
298 add(&mut facts, Risk::AlreadyCompiled, node)
299 }
300 "raise_statement" | "try_statement" => add(&mut facts, Risk::Exceptions, node),
301 "yield" => add(&mut facts, Risk::Generators, node),
302 "await" => add(&mut facts, Risk::Async, node),
303 "for_statement"
304 | "while_statement"
305 | "list_comprehension"
306 | "dictionary_comprehension"
307 | "generator_expression" => {
308 facts.loops += 1;
309 }
310 "class_definition" if node.child_by_field_name("superclasses").is_some() => {
311 add(&mut facts, Risk::ClassInheritance, node)
312 }
313 "function_definition" => {
314 if text(node, source).starts_with("async") {
315 add(&mut facts, Risk::Async, node);
316 }
317 if node.child_by_field_name("parameters").is_some_and(|p| {
318 named_children(p).iter().any(|c| {
319 c.kind() == "identifier"
320 && text(*c, source) != "self"
321 && text(*c, source) != "cls"
322 })
323 }) {
324 add(&mut facts, Risk::DynamicTyping, node);
325 }
326 }
327 "assignment" => {
328 let left = node
330 .child_by_field_name("left")
331 .map_or("", |l| text(l, source));
332 if left.contains('.')
333 && !left.starts_with("self.")
334 && left.chars().next().is_some_and(char::is_uppercase)
335 {
336 add(&mut facts, Risk::Monkeypatching, node);
337 }
338 }
339 _ => {}
340 });
341 facts
342}
343
344pub enum Resolution {
346 File(usize),
347 External(String),
348 Stdlib,
349 Unresolved,
350}
351
352pub fn resolve(from: &str, spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> Resolution {
354 let try_module = |base: &str| -> Option<usize> {
355 let base = base.trim_matches('/');
356 [format!("{base}.py"), format!("{base}/__init__.py")]
357 .iter()
358 .find_map(|c| index.get(c.as_str()).copied())
359 };
360 if spec.starts_with('.') {
361 let dots = spec.chars().take_while(|c| *c == '.').count();
362 let mut dir: Vec<&str> = from.split('/').collect();
363 dir.pop();
364 for _ in 1..dots {
365 dir.pop();
366 }
367 let rest = spec[dots..].replace('.', "/");
368 let base = if rest.is_empty() {
369 dir.join("/")
370 } else {
371 format!("{}/{rest}", dir.join("/"))
372 };
373 return try_module(&base).map_or(Resolution::Unresolved, Resolution::File);
374 }
375 let path = spec.replace('.', "/");
376 let roots: BTreeSet<&str> = ws
377 .packages
378 .iter()
379 .map(|p| p.src_root.as_str())
380 .chain([""])
381 .collect();
382 for root in roots {
383 let base = if root.is_empty() {
384 path.clone()
385 } else {
386 format!("{root}/{path}")
387 };
388 if let Some(i) = try_module(&base) {
389 return Resolution::File(i);
390 }
391 }
392 let top = spec.split('.').next().unwrap_or(spec);
393 if STDLIB.contains(&top) {
394 Resolution::Stdlib
395 } else if index
396 .keys()
397 .any(|p| p.starts_with(&format!("{top}/")) || p.contains(&format!("/{top}/")))
398 {
399 Resolution::Unresolved
401 } else {
402 Resolution::External(top.to_lowercase().replace('_', "-"))
403 }
404}
405
406const STDLIB: &[&str] = &[
407 "__future__",
408 "abc",
409 "argparse",
410 "array",
411 "ast",
412 "asyncio",
413 "base64",
414 "binascii",
415 "bisect",
416 "builtins",
417 "bz2",
418 "calendar",
419 "cmath",
420 "codecs",
421 "collections",
422 "colorsys",
423 "concurrent",
424 "contextlib",
425 "contextvars",
426 "copy",
427 "csv",
428 "ctypes",
429 "dataclasses",
430 "datetime",
431 "decimal",
432 "difflib",
433 "dis",
434 "email",
435 "enum",
436 "errno",
437 "fnmatch",
438 "fractions",
439 "functools",
440 "gc",
441 "getpass",
442 "gettext",
443 "glob",
444 "gzip",
445 "hashlib",
446 "heapq",
447 "hmac",
448 "html",
449 "http",
450 "importlib",
451 "inspect",
452 "io",
453 "ipaddress",
454 "itertools",
455 "json",
456 "keyword",
457 "locale",
458 "logging",
459 "lzma",
460 "math",
461 "mimetypes",
462 "multiprocessing",
463 "numbers",
464 "operator",
465 "os",
466 "pathlib",
467 "pickle",
468 "platform",
469 "pprint",
470 "queue",
471 "random",
472 "re",
473 "secrets",
474 "select",
475 "shlex",
476 "shutil",
477 "signal",
478 "socket",
479 "sqlite3",
480 "ssl",
481 "stat",
482 "statistics",
483 "string",
484 "struct",
485 "subprocess",
486 "sys",
487 "tempfile",
488 "textwrap",
489 "threading",
490 "time",
491 "timeit",
492 "tomllib",
493 "traceback",
494 "types",
495 "typing",
496 "typing_extensions",
497 "unicodedata",
498 "unittest",
499 "urllib",
500 "uuid",
501 "warnings",
502 "weakref",
503 "xml",
504 "zipfile",
505 "zlib",
506 "zoneinfo",
507];
508
509const fn m(crates: &'static str, fit: Fit, note: &'static str) -> CrateMatch {
512 CrateMatch { crates, fit, note }
513}
514
515pub fn lookup(package: &str) -> Option<CrateMatch> {
517 Some(match package {
518 "requests" | "httpx" | "urllib3" | "aiohttp" => m("reqwest", Fit::Good, ""),
519 "numpy" => m(
520 "ndarray",
521 Fit::Partial,
522 "Broadcasting and dtype rules differ; check numerics.",
523 ),
524 "pandas" => m(
525 "polars",
526 Fit::Partial,
527 "Different API; port by behavior, not by call.",
528 ),
529 "pyyaml" | "yaml" | "ruamel-yaml" => m(
530 "serde_yaml_ng, saphyr",
531 Fit::Partial,
532 "Round-tripping comments is not covered.",
533 ),
534 "regex" => m(
535 "fancy-regex",
536 Fit::Partial,
537 "Python `regex` features beyond fancy-regex need checks.",
538 ),
539 "click" | "typer" | "docopt" => m("clap", Fit::Good, ""),
540 "toml" | "tomli" | "tomli-w" => m("toml", Fit::Good, ""),
541 "pydantic" | "attrs" | "marshmallow" => m(
542 "serde, garde",
543 Fit::Partial,
544 "Validation errors will differ.",
545 ),
546 "jinja2" => m(
547 "minijinja",
548 Fit::Good,
549 "Same template language, by Jinja's author.",
550 ),
551 "lxml" | "beautifulsoup4" | "bs4" => m("quick-xml, scraper", Fit::Partial, ""),
552 "python-dateutil" | "dateutil" | "pendulum" | "arrow" => m("jiff", Fit::Good, ""),
553 "orjson" | "ujson" | "simplejson" => m("serde_json", Fit::Good, ""),
554 "rich" | "colorama" | "termcolor" => m("owo-colors, anstream", Fit::Good, ""),
555 "tqdm" => m("indicatif", Fit::Good, ""),
556 "cryptography" | "pycryptodome" => m("ring, RustCrypto crates", Fit::Partial, ""),
557 "pillow" | "pil" => m("image", Fit::Partial, ""),
558 "sqlalchemy" | "psycopg2" | "psycopg" => {
559 m("sqlx", Fit::Partial, "ORM layers port by hand.")
560 }
561 "django" | "flask" | "fastapi" | "starlette" => {
562 m("-", Fit::None, "Web framework: keep the app in Python.")
563 }
564 "pytest" | "hypothesis" | "mypy" => m("-", Fit::None, "Tooling, not runtime."),
565 _ => return None,
566 })
567}
568
569const SAFE_DECORATORS: &[&str] = &[
573 "cache",
574 "lru_cache",
575 "functools.cache",
576 "functools.lru_cache",
577 "staticmethod",
578];
579
580pub fn exports(path: &str, source: &str) -> (Vec<ExportedFn>, Vec<ExportedClass>) {
582 let Some(tree) = syntax::parse(&language(), source) else {
583 return (Vec::new(), Vec::new());
584 };
585 let root = tree.root_node();
586 let all = dunder_all(root, source);
587 let public = |name: &str| {
588 all.as_ref().map_or(!name.starts_with('_'), |names| {
589 names.iter().any(|n| n == name)
590 })
591 };
592 let mut functions = Vec::new();
593 let mut classes = Vec::new();
594 for item in named_children(root) {
595 let (decorators, definition) = unwrap_decorated(item, source);
596 match definition.kind() {
597 "function_definition" => {
598 let Some(f) = function(path, definition, source, &decorators, false) else {
599 continue;
600 };
601 if public(&f.name) {
602 functions.push(f);
603 }
604 }
605 "class_definition" => {
606 let Some(c) = class(path, definition, source, &decorators) else {
607 continue;
608 };
609 if public(&c.name) {
610 classes.push(c);
611 }
612 }
613 _ => {}
614 }
615 }
616 (functions, classes)
617}
618
619fn dunder_all(root: Node, source: &str) -> Option<Vec<String>> {
620 for statement in named_children(root) {
621 let assignment = named_children(statement)
622 .into_iter()
623 .find(|n| n.kind() == "assignment")?;
624 if assignment
625 .child_by_field_name("left")
626 .map(|l| text(l, source))
627 == Some("__all__")
628 {
629 let right = assignment.child_by_field_name("right")?;
630 return Some(
631 named_children(right)
632 .into_iter()
633 .filter(|n| n.kind() == "string")
634 .map(|n| {
635 text(n, source)
636 .trim_matches(|c| c == '"' || c == '\'')
637 .to_string()
638 })
639 .collect(),
640 );
641 }
642 }
643 None
644}
645
646fn unwrap_decorated<'t>(node: Node<'t>, source: &str) -> (Vec<String>, Node<'t>) {
647 if node.kind() != "decorated_definition" {
648 return (Vec::new(), node);
649 }
650 let decorators = named_children(node)
651 .into_iter()
652 .filter(|n| n.kind() == "decorator")
653 .map(|d| {
654 let t = text(d, source).trim_start_matches('@').trim();
655 t.split('(').next().unwrap_or(t).to_string()
656 })
657 .collect();
658 (
659 decorators,
660 node.child_by_field_name("definition").unwrap_or(node),
661 )
662}
663
664pub fn infer_numbers(params: &mut [Param], body: Node, source: &str) {
667 let unknown: Vec<String> = params
668 .iter()
669 .filter(|p| p.ts_type == "unknown" && p.default.is_none())
670 .map(|p| p.name.clone())
671 .collect();
672 if unknown.is_empty() {
673 return;
674 }
675 let mut numeric: Vec<String> = Vec::new();
676 let is_number = |n: Node| matches!(n.kind(), "integer" | "float");
677 syntax::walk(body, |n| {
678 let operands: Vec<Node> = match n.kind() {
679 "binary_operator" => {
680 let op = n
681 .child_by_field_name("operator")
682 .map_or("", |o| text(o, source));
683 let (Some(l), Some(r)) = (
684 n.child_by_field_name("left"),
685 n.child_by_field_name("right"),
686 ) else {
687 return;
688 };
689 match op {
690 "-" | "*" | "/" | "//" | "**" => vec![l, r],
691 "+" | "%" if is_number(l) || is_number(r) => vec![l, r],
692 _ => return,
693 }
694 }
695 "comparison_operator" => {
696 let parts = named_children(n);
697 if !parts.iter().any(|p| is_number(*p)) {
698 return;
699 }
700 parts
701 }
702 "call" => {
703 let f = n
704 .child_by_field_name("function")
705 .map_or("", |f| text(f, source));
706 if !matches!(
707 f,
708 "min" | "max" | "abs" | "round" | "float" | "int" | "divmod"
709 ) && !f.starts_with("math.")
710 {
711 return;
712 }
713 n.child_by_field_name("arguments")
714 .map(named_children)
715 .unwrap_or_default()
716 }
717 _ => return,
718 };
719 for o in operands {
720 if o.kind() == "identifier" {
721 let name = text(o, source).to_string();
722 if unknown.contains(&name) && !numeric.contains(&name) {
723 numeric.push(name);
724 }
725 }
726 }
727 });
728 for p in params.iter_mut().filter(|p| numeric.contains(&p.name)) {
729 p.ts_type = "number".into();
730 }
731}
732
733fn function(
734 path: &str,
735 node: Node,
736 source: &str,
737 decorators: &[String],
738 method: bool,
739) -> Option<ExportedFn> {
740 let name = text(node.child_by_field_name("name")?, source).to_string();
741 let (mut params, mut blocker) =
742 parameters(node.child_by_field_name("parameters")?, source, method);
743 let body = node.child_by_field_name("body");
744 if let Some(body) = body {
745 infer_numbers(&mut params, body, source);
746 }
747 let mut generator = false;
748 if let Some(body) = body {
749 syntax::walk(body, |n| {
750 if n.kind() == "yield" {
751 generator = true;
752 }
753 });
754 }
755 if let Some(body) = body {
757 let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
758 syntax::walk(body, |n| {
759 if n.kind() == "call"
760 && let Some(f) = n.child_by_field_name("function")
761 && f.kind() == "identifier"
762 && names.contains(&text(f, source))
763 && blocker.is_none()
764 {
765 blocker = Some(format!(
766 "calls its parameter `{}`: a callable",
767 text(f, source)
768 ));
769 }
770 });
771 }
772 if let Some(d) = decorators
773 .iter()
774 .find(|d| !SAFE_DECORATORS.contains(&d.as_str()))
775 {
776 blocker = blocker.or_else(|| Some(format!("decorated with `@{d}`")));
777 }
778 Some(ExportedFn {
779 name,
780 file: path.to_string(),
781 line: syntax::line(node),
782 params,
783 returns: node
784 .child_by_field_name("return_type")
785 .map_or_else(|| "unknown".into(), |r| to_ts_type(text(r, source))),
786 is_async: text(node, source).starts_with("async"),
787 is_generator: generator,
788 blocker,
789 ..Default::default()
790 })
791}
792
793fn parameters(node: Node, source: &str, method: bool) -> (Vec<Param>, Option<String>) {
795 let mut params = Vec::new();
796 let mut blocker = None;
797 let mut keyword_only = false;
798 for (i, p) in named_children(node).into_iter().enumerate() {
799 let name = |n: Option<Node>| n.map(|n| text(n, source).to_string()).unwrap_or_default();
800 let param = match p.kind() {
801 "identifier" => Param {
802 name: text(p, source).into(),
803 ts_type: "unknown".into(),
804 ..Default::default()
805 },
806 "typed_parameter" => {
807 let inner = named_children(p).into_iter().next();
808 let ty = p
809 .child_by_field_name("type")
810 .map_or_else(|| "unknown".into(), |t| to_ts_type(text(t, source)));
811 match inner.map(|n| n.kind()) {
812 Some("list_splat_pattern") => {
813 blocker = Some("takes `*args`".into());
814 continue;
815 }
816 Some("dictionary_splat_pattern") => {
817 blocker = Some("takes `**kwargs`".into());
818 continue;
819 }
820 _ => Param {
821 name: name(inner),
822 ts_type: ty,
823 ..Default::default()
824 },
825 }
826 }
827 "default_parameter" | "typed_default_parameter" => {
828 let value = p.child_by_field_name("value");
829 let default = value.map(|v| text(v, source).to_string());
830 let ty = match p.child_by_field_name("type") {
831 Some(t) => to_ts_type(text(t, source)),
832 None => match value.map(|v| v.kind()) {
833 Some("integer") => "int".into(),
834 Some("float") => "number".into(),
835 Some("string") => "string".into(),
836 Some("true" | "false") => "boolean".into(),
837 _ => "unknown".into(),
838 },
839 };
840 Param {
841 name: name(p.child_by_field_name("name")),
842 ts_type: ty,
843 optional: true,
844 default,
845 ..Default::default()
846 }
847 }
848 "list_splat_pattern" => {
849 blocker = Some("takes `*args`".into());
850 continue;
851 }
852 "dictionary_splat_pattern" => {
853 blocker = Some("takes `**kwargs`".into());
854 continue;
855 }
856 "keyword_separator" => {
857 keyword_only = true;
858 continue;
859 }
860 _ => continue,
861 };
862 if method && i == 0 && (param.name == "self" || param.name == "cls") {
863 continue;
864 }
865 params.push(Param {
866 keyword_only,
867 ..param
868 });
869 }
870 (params, blocker)
871}
872
873fn class(path: &str, node: Node, source: &str, decorators: &[String]) -> Option<ExportedClass> {
874 let name = text(node.child_by_field_name("name")?, source).to_string();
875 let mut blockers = Vec::new();
876 if let Some(bases) = node.child_by_field_name("superclasses") {
877 let bases: Vec<&str> = named_children(bases)
878 .into_iter()
879 .map(|b| text(b, source))
880 .filter(|b| *b != "object")
881 .collect();
882 if !bases.is_empty() {
883 blockers.push(format!("inherits from {}", bases.join(", ")));
884 }
885 }
886 if let Some(d) = decorators.first() {
887 blockers.push(format!("decorated with `@{d}`"));
888 }
889 let mut constructor = Vec::new();
890 let mut methods = Vec::new();
891 for item in named_children(node.child_by_field_name("body")?) {
892 let (decorators, definition) = unwrap_decorated(item, source);
893 match definition.kind() {
894 "function_definition" => {
895 let method_name = definition
896 .child_by_field_name("name")
897 .map_or("", |n| text(n, source));
898 if method_name == "__init__" {
899 let (params, blocker) =
900 parameters(definition.child_by_field_name("parameters")?, source, true);
901 constructor = params;
902 blockers.extend(blocker);
903 if let Some(body) = definition.child_by_field_name("body") {
905 syntax::walk(body, |n| {
906 if n.kind() == "assignment"
907 && let Some(left) = n.child_by_field_name("left")
908 && let Some(attr) = text(left, source).strip_prefix("self.")
909 && !attr.starts_with('_')
910 && !attr.contains('.')
911 {
912 blockers.push(format!("public attribute `{attr}`"));
913 }
914 });
915 }
916 } else if method_name.starts_with("__") && method_name.ends_with("__") {
917 blockers.push(format!("special method `{method_name}`"));
918 } else if method_name.starts_with('_') {
919 } else if let Some(d) = decorators.first() {
920 blockers.push(format!("`@{d}` method `{method_name}`"));
921 } else if let Some(f) = function(path, definition, source, &[], true) {
922 if f.is_async || f.is_generator {
923 blockers.push(format!("async or generator method `{}`", f.name));
924 }
925 if f.returns
926 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
927 .any(|w| w == name || w == "Self")
928 {
929 blockers.push(format!("method `{}` returns an instance", f.name));
930 }
931 methods.push(f);
932 }
933 }
934 "expression_statement" => {
935 let assignment = named_children(definition)
936 .into_iter()
937 .find(|n| n.kind() == "assignment");
938 if let Some(left) = assignment.and_then(|a| a.child_by_field_name("left")) {
939 let attr = text(left, source);
940 if !attr.starts_with('_') {
941 blockers.push(format!("public class attribute `{attr}`"));
942 }
943 }
944 }
945 _ => {}
946 }
947 }
948 blockers.sort();
949 blockers.dedup();
950 Some(ExportedClass {
951 name,
952 file: path.to_string(),
953 line: syntax::line(node),
954 constructor,
955 methods,
956 blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
957 })
958}
959
960pub fn to_ts_type(hint: &str) -> String {
963 let hint = hint.trim().trim_matches(|c| c == '"' || c == '\'');
964 let hint = hint.strip_prefix("typing.").unwrap_or(hint);
965 let top = split_top(hint, '|');
966 if top.len() > 1 {
967 return top
968 .iter()
969 .map(|p| to_ts_type(p))
970 .collect::<Vec<_>>()
971 .join(" | ");
972 }
973 let (head, args) = match hint.find('[') {
974 Some(i) if hint.ends_with(']') => {
975 (&hint[..i], split_top(&hint[i + 1..hint.len() - 1], ','))
976 }
977 _ => (hint, Vec::new()),
978 };
979 let head = head.trim().strip_prefix("typing.").unwrap_or(head.trim());
980 let arg = |i: usize| {
981 args.get(i)
982 .map_or_else(|| "unknown".to_string(), |a| to_ts_type(a))
983 };
984 match head {
985 "str" => "string".into(),
986 "int" => "int".into(),
987 "float" => "number".into(),
988 "bool" => "boolean".into(),
989 "None" | "NoneType" => "undefined".into(),
990 "list" | "List" | "Sequence" | "Iterable" | "MutableSequence" | "Collection" => {
991 format!("{}[]", wrap(&arg(0)))
992 }
993 "Optional" => format!("{} | undefined", arg(0)),
994 "Union" => args
995 .iter()
996 .map(|a| to_ts_type(a))
997 .collect::<Vec<_>>()
998 .join(" | "),
999 "dict" | "Dict" | "Mapping" | "MutableMapping" if arg(0) == "string" => {
1000 format!("Record<string, {}>", arg(1))
1001 }
1002 "Literal" => args
1003 .iter()
1004 .map(|a| a.trim().replace('"', "'"))
1005 .collect::<Vec<_>>()
1006 .join(" | "),
1007 "Callable" => "(...args: unknown[]) => unknown".into(),
1008 "Any" | "object" => "unknown".into(),
1009 other => other.to_string(),
1011 }
1012}
1013
1014fn wrap(ts: &str) -> String {
1015 if ts.contains('|') {
1016 format!("({ts})")
1017 } else {
1018 ts.to_string()
1019 }
1020}
1021
1022fn split_top(text: &str, sep: char) -> Vec<String> {
1023 let mut out = Vec::new();
1024 let mut depth = 0i32;
1025 let mut current = String::new();
1026 for c in text.chars() {
1027 match c {
1028 '[' | '(' => depth += 1,
1029 ']' | ')' => depth -= 1,
1030 _ => {}
1031 }
1032 if c == sep && depth == 0 {
1033 out.push(current.trim().to_string());
1034 current.clear();
1035 } else {
1036 current.push(c);
1037 }
1038 }
1039 if !current.trim().is_empty() {
1040 out.push(current.trim().to_string());
1041 }
1042 out
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047 use super::*;
1048
1049 #[test]
1050 fn maps_type_hints() {
1051 assert_eq!(to_ts_type("list[str]"), "string[]");
1052 assert_eq!(to_ts_type("Optional[int]"), "int | undefined");
1053 assert_eq!(to_ts_type("str | None"), "string | undefined");
1054 assert_eq!(
1055 to_ts_type("dict[str, list[float]]"),
1056 "Record<string, number[]>"
1057 );
1058 assert_eq!(to_ts_type("Literal['a', \"b\"]"), "'a' | 'b'");
1059 assert!(to_ts_type("Callable[[int], str]").contains("=>"));
1060 assert_eq!(to_ts_type("tuple[int, int]"), "tuple");
1061 }
1062
1063 #[test]
1064 fn reads_exports() {
1065 let source = "__all__ = ['slug', 'Counter']\n\n\
1066 def slug(text: str, sep: str = '-', *, lower=True) -> str:\n return text\n\n\
1067 def hidden(x): pass\n\n\
1068 @lru_cache\ndef cached(n: int) -> int:\n return n\n\n\
1069 def gen(n: int):\n yield n\n\n\
1070 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\
1071 class Point:\n def __init__(self, x):\n self.x = x\n";
1072 let (functions, classes) = exports("m.py", source);
1073 assert_eq!(
1074 functions
1075 .iter()
1076 .map(|f| f.name.as_str())
1077 .collect::<Vec<_>>(),
1078 ["slug"]
1079 );
1080 let slug = &functions[0];
1081 assert_eq!(slug.params[1].default.as_deref(), Some("'-'"));
1082 assert!(slug.params[2].keyword_only && slug.params[2].ts_type == "boolean");
1083 assert_eq!(slug.returns, "string");
1084 assert_eq!(classes.len(), 1);
1085 assert!(classes[0].blocker.is_none());
1086 assert_eq!(classes[0].methods.len(), 1);
1087
1088 let (all, classes) = exports(
1089 "n.py",
1090 &source.replace("__all__ = ['slug', 'Counter']\n", ""),
1091 );
1092 let names: Vec<&str> = all.iter().map(|f| f.name.as_str()).collect();
1093 assert_eq!(names, ["slug", "hidden", "cached", "gen"]);
1094 assert!(all[3].is_generator);
1095 assert!(
1096 classes[1]
1097 .blocker
1098 .as_deref()
1099 .unwrap()
1100 .contains("public attribute `x`")
1101 );
1102 }
1103
1104 #[test]
1105 fn scans_risks_and_imports() {
1106 let facts = scan(
1107 "import os\nfrom .util import helper\nimport re\nx = 7 // 2\nre.compile(r'(?<=a)b')\nfor i in range(3): pass\n",
1108 );
1109 let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1110 assert!(
1111 specs.contains(&"os") && specs.contains(&".util") && specs.contains(&".util.helper")
1112 );
1113 assert!(facts.risks.contains_key(&Risk::DivisionSemantics));
1114 assert!(facts.risks.contains_key(&Risk::RegexSyntax));
1115 assert_eq!(facts.loops, 1);
1116 }
1117
1118 #[test]
1119 fn infers_numbers_from_arithmetic() {
1120 let src = "def rgb_to_hsv(r, g, b):\n maxc = max(r, g, b)\n return maxc - r\n\n\
1121 def greet(name):\n return 'hi ' + name\n";
1122 let (fns, _) = exports("colorsys.py", src);
1123 let types: Vec<&str> = fns[0].params.iter().map(|p| p.ts_type.as_str()).collect();
1124 assert_eq!(types, ["number", "number", "number"]);
1125 assert_eq!(fns[1].params[0].ts_type, "unknown");
1126 }
1127}