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 = 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] = &[
406 "__future__",
407 "abc",
408 "argparse",
409 "array",
410 "ast",
411 "asyncio",
412 "base64",
413 "binascii",
414 "bisect",
415 "builtins",
416 "bz2",
417 "calendar",
418 "cmath",
419 "codecs",
420 "collections",
421 "colorsys",
422 "concurrent",
423 "contextlib",
424 "contextvars",
425 "copy",
426 "csv",
427 "ctypes",
428 "dataclasses",
429 "datetime",
430 "decimal",
431 "difflib",
432 "dis",
433 "email",
434 "enum",
435 "errno",
436 "fnmatch",
437 "fractions",
438 "functools",
439 "gc",
440 "getpass",
441 "gettext",
442 "glob",
443 "gzip",
444 "hashlib",
445 "heapq",
446 "hmac",
447 "html",
448 "http",
449 "importlib",
450 "inspect",
451 "io",
452 "ipaddress",
453 "itertools",
454 "json",
455 "keyword",
456 "locale",
457 "logging",
458 "lzma",
459 "math",
460 "mimetypes",
461 "multiprocessing",
462 "numbers",
463 "operator",
464 "os",
465 "pathlib",
466 "pickle",
467 "platform",
468 "pprint",
469 "queue",
470 "random",
471 "re",
472 "secrets",
473 "select",
474 "shlex",
475 "shutil",
476 "signal",
477 "socket",
478 "sqlite3",
479 "ssl",
480 "stat",
481 "statistics",
482 "string",
483 "struct",
484 "subprocess",
485 "sys",
486 "tempfile",
487 "textwrap",
488 "threading",
489 "time",
490 "timeit",
491 "tomllib",
492 "traceback",
493 "types",
494 "typing",
495 "typing_extensions",
496 "unicodedata",
497 "unittest",
498 "urllib",
499 "uuid",
500 "warnings",
501 "weakref",
502 "xml",
503 "zipfile",
504 "zlib",
505 "zoneinfo",
506];
507
508const fn m(crates: &'static str, fit: Fit, note: &'static str) -> CrateMatch {
511 CrateMatch { crates, fit, note }
512}
513
514pub fn lookup(package: &str) -> Option<CrateMatch> {
516 Some(match package {
517 "requests" | "httpx" | "urllib3" | "aiohttp" => m("reqwest", Fit::Good, ""),
518 "numpy" => m(
519 "ndarray",
520 Fit::Partial,
521 "Broadcasting and dtype rules differ; check numerics.",
522 ),
523 "pandas" => m(
524 "polars",
525 Fit::Partial,
526 "Different API; port by behavior, not by call.",
527 ),
528 "pyyaml" | "yaml" | "ruamel-yaml" => m(
529 "serde_yaml_ng, saphyr",
530 Fit::Partial,
531 "Round-tripping comments is not covered.",
532 ),
533 "regex" => m(
534 "fancy-regex",
535 Fit::Partial,
536 "Python `regex` features beyond fancy-regex need checks.",
537 ),
538 "click" | "typer" | "docopt" => m("clap", Fit::Good, ""),
539 "toml" | "tomli" | "tomli-w" => m("toml", Fit::Good, ""),
540 "pydantic" | "attrs" | "marshmallow" => m(
541 "serde, garde",
542 Fit::Partial,
543 "Validation errors will differ.",
544 ),
545 "jinja2" => m(
546 "minijinja",
547 Fit::Good,
548 "Same template language, by Jinja's author.",
549 ),
550 "lxml" | "beautifulsoup4" | "bs4" => m("quick-xml, scraper", Fit::Partial, ""),
551 "python-dateutil" | "dateutil" | "pendulum" | "arrow" => m("jiff", Fit::Good, ""),
552 "orjson" | "ujson" | "simplejson" => m("serde_json", Fit::Good, ""),
553 "rich" | "colorama" | "termcolor" => m("owo-colors, anstream", Fit::Good, ""),
554 "tqdm" => m("indicatif", Fit::Good, ""),
555 "cryptography" | "pycryptodome" => m("ring, RustCrypto crates", Fit::Partial, ""),
556 "pillow" | "pil" => m("image", Fit::Partial, ""),
557 "sqlalchemy" | "psycopg2" | "psycopg" => {
558 m("sqlx", Fit::Partial, "ORM layers port by hand.")
559 }
560 "django" | "flask" | "fastapi" | "starlette" => {
561 m("-", Fit::None, "Web framework: keep the app in Python.")
562 }
563 "pytest" | "hypothesis" | "mypy" => m("-", Fit::None, "Tooling, not runtime."),
564 _ => return None,
565 })
566}
567
568const SAFE_DECORATORS: &[&str] = &[
572 "cache",
573 "lru_cache",
574 "functools.cache",
575 "functools.lru_cache",
576 "staticmethod",
577];
578
579pub fn exports(path: &str, source: &str) -> (Vec<ExportedFn>, Vec<ExportedClass>) {
581 let Some(tree) = syntax::parse(&language(), source) else {
582 return (Vec::new(), Vec::new());
583 };
584 let root = tree.root_node();
585 let all = dunder_all(root, source);
586 let public = |name: &str| {
587 all.as_ref().map_or(!name.starts_with('_'), |names| {
588 names.iter().any(|n| n == name)
589 })
590 };
591 let mut functions = Vec::new();
592 let mut classes = Vec::new();
593 for item in named_children(root) {
594 let (decorators, definition) = unwrap_decorated(item, source);
595 match definition.kind() {
596 "function_definition" => {
597 let Some(f) = function(path, definition, source, &decorators, false) else {
598 continue;
599 };
600 if public(&f.name) {
601 functions.push(f);
602 }
603 }
604 "class_definition" => {
605 let Some(c) = class(path, definition, source, &decorators) else {
606 continue;
607 };
608 if public(&c.name) {
609 classes.push(c);
610 }
611 }
612 _ => {}
613 }
614 }
615 (functions, classes)
616}
617
618fn dunder_all(root: Node, source: &str) -> Option<Vec<String>> {
619 for statement in named_children(root) {
620 let assignment = named_children(statement)
621 .into_iter()
622 .find(|n| n.kind() == "assignment")?;
623 if assignment
624 .child_by_field_name("left")
625 .map(|l| text(l, source))
626 == Some("__all__")
627 {
628 let right = assignment.child_by_field_name("right")?;
629 return Some(
630 named_children(right)
631 .into_iter()
632 .filter(|n| n.kind() == "string")
633 .map(|n| {
634 text(n, source)
635 .trim_matches(|c| c == '"' || c == '\'')
636 .to_string()
637 })
638 .collect(),
639 );
640 }
641 }
642 None
643}
644
645fn unwrap_decorated<'t>(node: Node<'t>, source: &str) -> (Vec<String>, Node<'t>) {
646 if node.kind() != "decorated_definition" {
647 return (Vec::new(), node);
648 }
649 let decorators = named_children(node)
650 .into_iter()
651 .filter(|n| n.kind() == "decorator")
652 .map(|d| {
653 let t = text(d, source).trim_start_matches('@').trim();
654 t.split('(').next().unwrap_or(t).to_string()
655 })
656 .collect();
657 (
658 decorators,
659 node.child_by_field_name("definition").unwrap_or(node),
660 )
661}
662
663pub fn infer_numbers(params: &mut [Param], body: Node, source: &str) {
666 let unknown: Vec<String> = params
667 .iter()
668 .filter(|p| p.ts_type == "unknown" && p.default.is_none())
669 .map(|p| p.name.clone())
670 .collect();
671 if unknown.is_empty() {
672 return;
673 }
674 let mut numeric: Vec<String> = Vec::new();
675 let is_number = |n: Node| matches!(n.kind(), "integer" | "float");
676 syntax::walk(body, |n| {
677 let operands: Vec<Node> = match n.kind() {
678 "binary_operator" => {
679 let op = n
680 .child_by_field_name("operator")
681 .map_or("", |o| text(o, source));
682 let (Some(l), Some(r)) = (
683 n.child_by_field_name("left"),
684 n.child_by_field_name("right"),
685 ) else {
686 return;
687 };
688 match op {
689 "-" | "*" | "/" | "//" | "**" => vec![l, r],
690 "+" | "%" if is_number(l) || is_number(r) => vec![l, r],
691 _ => return,
692 }
693 }
694 "comparison_operator" => {
695 let parts = named_children(n);
696 if !parts.iter().any(|p| is_number(*p)) {
697 return;
698 }
699 parts
700 }
701 "call" => {
702 let f = n
703 .child_by_field_name("function")
704 .map_or("", |f| text(f, source));
705 if !matches!(
706 f,
707 "min" | "max" | "abs" | "round" | "float" | "int" | "divmod"
708 ) && !f.starts_with("math.")
709 {
710 return;
711 }
712 n.child_by_field_name("arguments")
713 .map(named_children)
714 .unwrap_or_default()
715 }
716 _ => return,
717 };
718 for o in operands {
719 if o.kind() == "identifier" {
720 let name = text(o, source).to_string();
721 if unknown.contains(&name) && !numeric.contains(&name) {
722 numeric.push(name);
723 }
724 }
725 }
726 });
727 for p in params.iter_mut().filter(|p| numeric.contains(&p.name)) {
728 p.ts_type = "number".into();
729 }
730}
731
732fn function(
733 path: &str,
734 node: Node,
735 source: &str,
736 decorators: &[String],
737 method: bool,
738) -> Option<ExportedFn> {
739 let name = text(node.child_by_field_name("name")?, source).to_string();
740 let (mut params, mut blocker) =
741 parameters(node.child_by_field_name("parameters")?, source, method);
742 let body = node.child_by_field_name("body");
743 if let Some(body) = body {
744 infer_numbers(&mut params, body, source);
745 }
746 let mut generator = false;
747 if let Some(body) = body {
748 syntax::walk(body, |n| {
749 if n.kind() == "yield" {
750 generator = true;
751 }
752 });
753 }
754 if let Some(body) = body {
756 let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
757 syntax::walk(body, |n| {
758 if n.kind() == "call"
759 && let Some(f) = n.child_by_field_name("function")
760 && f.kind() == "identifier"
761 && names.contains(&text(f, source))
762 && blocker.is_none()
763 {
764 blocker = Some(format!(
765 "calls its parameter `{}`: a callable",
766 text(f, source)
767 ));
768 }
769 });
770 }
771 if let Some(d) = decorators
772 .iter()
773 .find(|d| !SAFE_DECORATORS.contains(&d.as_str()))
774 {
775 blocker = blocker.or_else(|| Some(format!("decorated with `@{d}`")));
776 }
777 Some(ExportedFn {
778 name,
779 file: path.to_string(),
780 line: syntax::line(node),
781 params,
782 returns: node
783 .child_by_field_name("return_type")
784 .map_or_else(|| "unknown".into(), |r| to_ts_type(text(r, source))),
785 is_async: text(node, source).starts_with("async"),
786 is_generator: generator,
787 blocker,
788 ..Default::default()
789 })
790}
791
792fn parameters(node: Node, source: &str, method: bool) -> (Vec<Param>, Option<String>) {
794 let mut params = Vec::new();
795 let mut blocker = None;
796 let mut keyword_only = false;
797 for (i, p) in named_children(node).into_iter().enumerate() {
798 let name = |n: Option<Node>| n.map(|n| text(n, source).to_string()).unwrap_or_default();
799 let param = match p.kind() {
800 "identifier" => Param {
801 name: text(p, source).into(),
802 ts_type: "unknown".into(),
803 ..Default::default()
804 },
805 "typed_parameter" => {
806 let inner = named_children(p).into_iter().next();
807 let ty = p
808 .child_by_field_name("type")
809 .map_or_else(|| "unknown".into(), |t| to_ts_type(text(t, source)));
810 match inner.map(|n| n.kind()) {
811 Some("list_splat_pattern") => {
812 blocker = Some("takes `*args`".into());
813 continue;
814 }
815 Some("dictionary_splat_pattern") => {
816 blocker = Some("takes `**kwargs`".into());
817 continue;
818 }
819 _ => Param {
820 name: name(inner),
821 ts_type: ty,
822 ..Default::default()
823 },
824 }
825 }
826 "default_parameter" | "typed_default_parameter" => {
827 let value = p.child_by_field_name("value");
828 let default = value.map(|v| text(v, source).to_string());
829 let ty = match p.child_by_field_name("type") {
830 Some(t) => to_ts_type(text(t, source)),
831 None => match value.map(|v| v.kind()) {
832 Some("integer") => "int".into(),
833 Some("float") => "number".into(),
834 Some("string") => "string".into(),
835 Some("true" | "false") => "boolean".into(),
836 _ => "unknown".into(),
837 },
838 };
839 Param {
840 name: name(p.child_by_field_name("name")),
841 ts_type: ty,
842 optional: true,
843 default,
844 ..Default::default()
845 }
846 }
847 "list_splat_pattern" => {
848 blocker = Some("takes `*args`".into());
849 continue;
850 }
851 "dictionary_splat_pattern" => {
852 blocker = Some("takes `**kwargs`".into());
853 continue;
854 }
855 "keyword_separator" => {
856 keyword_only = true;
857 continue;
858 }
859 _ => continue,
860 };
861 if method && i == 0 && (param.name == "self" || param.name == "cls") {
862 continue;
863 }
864 params.push(Param {
865 keyword_only,
866 ..param
867 });
868 }
869 (params, blocker)
870}
871
872fn class(path: &str, node: Node, source: &str, decorators: &[String]) -> Option<ExportedClass> {
873 let name = text(node.child_by_field_name("name")?, source).to_string();
874 let mut blockers = Vec::new();
875 if let Some(bases) = node.child_by_field_name("superclasses") {
876 let bases: Vec<&str> = named_children(bases)
877 .into_iter()
878 .map(|b| text(b, source))
879 .filter(|b| *b != "object")
880 .collect();
881 if !bases.is_empty() {
882 blockers.push(format!("inherits from {}", bases.join(", ")));
883 }
884 }
885 if let Some(d) = decorators.first() {
886 blockers.push(format!("decorated with `@{d}`"));
887 }
888 let mut constructor = Vec::new();
889 let mut methods = Vec::new();
890 for item in named_children(node.child_by_field_name("body")?) {
891 let (decorators, definition) = unwrap_decorated(item, source);
892 match definition.kind() {
893 "function_definition" => {
894 let method_name = definition
895 .child_by_field_name("name")
896 .map_or("", |n| text(n, source));
897 if method_name == "__init__" {
898 let (params, blocker) =
899 parameters(definition.child_by_field_name("parameters")?, source, true);
900 constructor = params;
901 blockers.extend(blocker);
902 if let Some(body) = definition.child_by_field_name("body") {
904 syntax::walk(body, |n| {
905 if n.kind() == "assignment"
906 && let Some(left) = n.child_by_field_name("left")
907 && let Some(attr) = text(left, source).strip_prefix("self.")
908 && !attr.starts_with('_')
909 && !attr.contains('.')
910 {
911 blockers.push(format!("public attribute `{attr}`"));
912 }
913 });
914 }
915 } else if method_name.starts_with("__") && method_name.ends_with("__") {
916 blockers.push(format!("special method `{method_name}`"));
917 } else if method_name.starts_with('_') {
918 } else if let Some(d) = decorators.first() {
919 blockers.push(format!("`@{d}` method `{method_name}`"));
920 } else if let Some(f) = function(path, definition, source, &[], true) {
921 if f.is_async || f.is_generator {
922 blockers.push(format!("async or generator method `{}`", f.name));
923 }
924 if f.returns
925 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
926 .any(|w| w == name || w == "Self")
927 {
928 blockers.push(format!("method `{}` returns an instance", f.name));
929 }
930 methods.push(f);
931 }
932 }
933 "expression_statement" => {
934 let assignment = named_children(definition)
935 .into_iter()
936 .find(|n| n.kind() == "assignment");
937 if let Some(left) = assignment.and_then(|a| a.child_by_field_name("left")) {
938 let attr = text(left, source);
939 if !attr.starts_with('_') {
940 blockers.push(format!("public class attribute `{attr}`"));
941 }
942 }
943 }
944 _ => {}
945 }
946 }
947 blockers.sort();
948 blockers.dedup();
949 Some(ExportedClass {
950 name,
951 file: path.to_string(),
952 line: syntax::line(node),
953 constructor,
954 methods,
955 blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
956 })
957}
958
959pub fn to_ts_type(hint: &str) -> String {
962 let hint = hint.trim().trim_matches(|c| c == '"' || c == '\'');
963 let hint = hint.strip_prefix("typing.").unwrap_or(hint);
964 let top = split_top(hint, '|');
965 if top.len() > 1 {
966 return top
967 .iter()
968 .map(|p| to_ts_type(p))
969 .collect::<Vec<_>>()
970 .join(" | ");
971 }
972 let (head, args) = match hint.find('[') {
973 Some(i) if hint.ends_with(']') => {
974 (&hint[..i], split_top(&hint[i + 1..hint.len() - 1], ','))
975 }
976 _ => (hint, Vec::new()),
977 };
978 let head = head.trim().strip_prefix("typing.").unwrap_or(head.trim());
979 let arg = |i: usize| {
980 args.get(i)
981 .map_or_else(|| "unknown".to_string(), |a| to_ts_type(a))
982 };
983 match head {
984 "str" => "string".into(),
985 "int" => "int".into(),
986 "float" => "number".into(),
987 "bool" => "boolean".into(),
988 "None" | "NoneType" => "undefined".into(),
989 "list" | "List" | "Sequence" | "Iterable" | "MutableSequence" | "Collection" => {
990 format!("{}[]", wrap(&arg(0)))
991 }
992 "Optional" => format!("{} | undefined", arg(0)),
993 "Union" => args
994 .iter()
995 .map(|a| to_ts_type(a))
996 .collect::<Vec<_>>()
997 .join(" | "),
998 "dict" | "Dict" | "Mapping" | "MutableMapping" if arg(0) == "string" => {
999 format!("Record<string, {}>", arg(1))
1000 }
1001 "Literal" => args
1002 .iter()
1003 .map(|a| a.trim().replace('"', "'"))
1004 .collect::<Vec<_>>()
1005 .join(" | "),
1006 "Callable" => "(...args: unknown[]) => unknown".into(),
1007 "Any" | "object" => "unknown".into(),
1008 other => other.to_string(),
1010 }
1011}
1012
1013fn wrap(ts: &str) -> String {
1014 if ts.contains('|') {
1015 format!("({ts})")
1016 } else {
1017 ts.to_string()
1018 }
1019}
1020
1021fn split_top(text: &str, sep: char) -> Vec<String> {
1022 let mut out = Vec::new();
1023 let mut depth = 0i32;
1024 let mut current = String::new();
1025 for c in text.chars() {
1026 match c {
1027 '[' | '(' => depth += 1,
1028 ']' | ')' => depth -= 1,
1029 _ => {}
1030 }
1031 if c == sep && depth == 0 {
1032 out.push(current.trim().to_string());
1033 current.clear();
1034 } else {
1035 current.push(c);
1036 }
1037 }
1038 if !current.trim().is_empty() {
1039 out.push(current.trim().to_string());
1040 }
1041 out
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046 use super::*;
1047
1048 #[test]
1049 fn maps_type_hints() {
1050 assert_eq!(to_ts_type("list[str]"), "string[]");
1051 assert_eq!(to_ts_type("Optional[int]"), "int | undefined");
1052 assert_eq!(to_ts_type("str | None"), "string | undefined");
1053 assert_eq!(
1054 to_ts_type("dict[str, list[float]]"),
1055 "Record<string, number[]>"
1056 );
1057 assert_eq!(to_ts_type("Literal['a', \"b\"]"), "'a' | 'b'");
1058 assert!(to_ts_type("Callable[[int], str]").contains("=>"));
1059 assert_eq!(to_ts_type("tuple[int, int]"), "tuple");
1060 }
1061
1062 #[test]
1063 fn reads_exports() {
1064 let source = "__all__ = ['slug', 'Counter']\n\n\
1065 def slug(text: str, sep: str = '-', *, lower=True) -> str:\n return text\n\n\
1066 def hidden(x): pass\n\n\
1067 @lru_cache\ndef cached(n: int) -> int:\n return n\n\n\
1068 def gen(n: int):\n yield n\n\n\
1069 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\
1070 class Point:\n def __init__(self, x):\n self.x = x\n";
1071 let (functions, classes) = exports("m.py", source);
1072 assert_eq!(
1073 functions
1074 .iter()
1075 .map(|f| f.name.as_str())
1076 .collect::<Vec<_>>(),
1077 ["slug"]
1078 );
1079 let slug = &functions[0];
1080 assert_eq!(slug.params[1].default.as_deref(), Some("'-'"));
1081 assert!(slug.params[2].keyword_only && slug.params[2].ts_type == "boolean");
1082 assert_eq!(slug.returns, "string");
1083 assert_eq!(classes.len(), 1);
1084 assert!(classes[0].blocker.is_none());
1085 assert_eq!(classes[0].methods.len(), 1);
1086
1087 let (all, classes) = exports(
1088 "n.py",
1089 &source.replace("__all__ = ['slug', 'Counter']\n", ""),
1090 );
1091 let names: Vec<&str> = all.iter().map(|f| f.name.as_str()).collect();
1092 assert_eq!(names, ["slug", "hidden", "cached", "gen"]);
1093 assert!(all[3].is_generator);
1094 assert!(
1095 classes[1]
1096 .blocker
1097 .as_deref()
1098 .unwrap()
1099 .contains("public attribute `x`")
1100 );
1101 }
1102
1103 #[test]
1104 fn scans_risks_and_imports() {
1105 let facts = scan(
1106 "import os\nfrom .util import helper\nimport re\nx = 7 // 2\nre.compile(r'(?<=a)b')\nfor i in range(3): pass\n",
1107 );
1108 let specs: Vec<&str> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
1109 assert!(
1110 specs.contains(&"os") && specs.contains(&".util") && specs.contains(&".util.helper")
1111 );
1112 assert!(facts.risks.contains_key(&Risk::DivisionSemantics));
1113 assert!(facts.risks.contains_key(&Risk::RegexSyntax));
1114 assert_eq!(facts.loops, 1);
1115 }
1116
1117 #[test]
1118 fn infers_numbers_from_arithmetic() {
1119 let src = "def rgb_to_hsv(r, g, b):\n maxc = max(r, g, b)\n return maxc - r\n\n\
1120 def greet(name):\n return 'hi ' + name\n";
1121 let (fns, _) = exports("colorsys.py", src);
1122 let types: Vec<&str> = fns[0].params.iter().map(|p| p.ts_type.as_str()).collect();
1123 assert_eq!(types, ["number", "number", "number"]);
1124 assert_eq!(fns[1].params[0].ts_type, "unknown");
1125 }
1126}