1use camino::Utf8Path;
13use ruff_python_ast::token::TokenKind;
14use ruff_python_ast::visitor::{walk_expr, walk_stmt, Visitor};
15use ruff_python_ast::{
16 Expr, ExprContext, Parameters, Stmt, StmtClassDef, StmtFunctionDef, StmtImport, StmtImportFrom,
17};
18use ruff_python_parser::parse_module;
19use ruff_source_file::LineIndex;
20use ruff_text_size::{Ranged, TextRange, TextSize};
21use std::collections::{HashMap, HashSet};
22
23#[derive(Debug, thiserror::Error)]
24pub enum ParseError {
25 #[error("failed to initialize the Python grammar")]
26 Grammar,
27 #[error("parser produced no tree for {0}")]
28 NoTree(String),
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum DefKind {
34 Function,
35 Class,
36 Variable,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Definition {
43 pub name: String,
44 pub kind: DefKind,
45 pub line: u32,
46 pub end_line: u32,
47 pub private_by_convention: bool,
49 pub decorators: Vec<String>,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Import {
57 pub module: String,
60 pub relative_dots: u8,
62 pub names: Vec<String>,
64 pub bindings: Vec<String>,
67 pub is_star: bool,
69 pub type_checking_only: bool,
72 pub redundant: Vec<bool>,
76 pub in_try: bool,
81 pub line: u32,
82 pub end_line: u32,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct FunctionComplexity {
91 pub name: String,
92 pub line: u32,
93 pub end_line: u32,
95 pub cyclomatic: u32,
97 pub cognitive: u32,
99 pub params_total: u32,
101 pub params_annotated: u32,
103 pub return_annotated: bool,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct SecurityHit {
111 pub rule: &'static str,
113 pub line: u32,
114 pub detail: String,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct CallSite {
120 pub callee: String,
121 pub line: u32,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct ScopeFinding {
127 pub name: String,
128 pub line: u32,
129 pub is_param: bool,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct ClassInfo {
138 pub name: String,
139 pub line: u32,
140 pub end_line: u32,
141 pub is_private: bool,
143 pub decorators: Vec<String>,
145 pub bases: Vec<String>,
147 pub is_enum: bool,
149 pub methods: Vec<(String, Vec<String>)>,
151 pub members: Vec<ClassMember>,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct ClassMember {
159 pub name: String,
160 pub line: u32,
161 pub end_line: u32,
162 pub is_method: bool,
164 pub is_private: bool,
165 pub decorators: Vec<String>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct UnreachableCode {
174 pub line: u32,
175 pub after: &'static str,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct TypeLeak {
183 pub function: String,
185 pub type_name: String,
187 pub line: u32,
188 pub is_return: bool,
190}
191
192#[derive(Debug, Clone)]
194pub struct ParsedModule {
195 pub path: camino::Utf8PathBuf,
196 pub definitions: Vec<Definition>,
197 pub imports: Vec<Import>,
198 pub nested_imports: Vec<Import>,
202 pub calls: Vec<CallSite>,
203 pub functions: Vec<FunctionComplexity>,
204 pub security_hits: Vec<SecurityHit>,
205 pub dunder_all: Option<Vec<String>>,
206 pub dunder_all_dynamic: bool,
211 pub used_names: Vec<String>,
212 pub local_uses: Vec<String>,
213 pub attr_accessed: Vec<String>,
218 pub module_used: Vec<String>,
224 pub ignores: Vec<(u32, String)>,
225 pub scope_findings: Vec<ScopeFinding>,
226 pub classes: Vec<ClassInfo>,
227 pub unreachable: Vec<UnreachableCode>,
229 pub type_leaks: Vec<TypeLeak>,
231 pub name_counts: HashMap<String, u32>,
232 pub has_dynamic_sink: bool,
233 pub has_main_guard: bool,
236 pub halstead_volume: f64,
237 had_errors: bool,
238}
239
240impl ParsedModule {
241 pub fn had_errors(&self) -> bool {
243 self.had_errors
244 }
245}
246
247#[derive(Default)]
250pub struct PyParser;
251
252impl PyParser {
253 pub fn new() -> Result<Self, ParseError> {
254 Ok(Self)
255 }
256
257 pub fn parse(&mut self, path: &Utf8Path, source: &str) -> Result<ParsedModule, ParseError> {
259 let li = LineIndex::from_source_text(source);
260 let mut m = ParsedModule {
261 path: path.to_owned(),
262 definitions: Vec::new(),
263 imports: Vec::new(),
264 nested_imports: Vec::new(),
265 calls: Vec::new(),
266 functions: Vec::new(),
267 security_hits: Vec::new(),
268 dunder_all: None,
269 dunder_all_dynamic: false,
270 used_names: Vec::new(),
271 local_uses: Vec::new(),
272 attr_accessed: Vec::new(),
273 module_used: Vec::new(),
274 ignores: Vec::new(),
275 scope_findings: Vec::new(),
276 classes: Vec::new(),
277 unreachable: Vec::new(),
278 type_leaks: Vec::new(),
279 name_counts: HashMap::new(),
280 has_dynamic_sink: false,
281 has_main_guard: false,
282 halstead_volume: 0.0,
283 had_errors: false,
284 };
285
286 let parsed = match parse_module(source) {
287 Ok(p) => p,
288 Err(_) => {
289 m.had_errors = true;
291 return Ok(m);
292 }
293 };
294 m.had_errors = !parsed.errors().is_empty();
295 let module = parsed.syntax();
296
297 let mut name_tokens: Vec<(TextSize, &str)> = Vec::new();
301 let mut h_total_ops = 0u64;
302 let mut h_total_oprs = 0u64;
303 let mut h_ops: HashSet<TokenKind> = HashSet::new();
304 let mut h_oprs: HashSet<&str> = HashSet::new();
305 for tok in parsed.tokens() {
306 let kind = tok.kind();
307 let text = &source[tok.range()];
308 if kind == TokenKind::Name {
309 *m.name_counts.entry(text.to_string()).or_insert(0) += 1;
310 m.used_names.push(text.to_string());
311 name_tokens.push((tok.range().start(), text));
312 }
313 if kind == TokenKind::Comment {
314 let line = line1(&li, tok.range().start());
315 if let Some(rules) = parse_ignore_comment(text) {
316 for r in rules {
317 m.ignores.push((line, r));
318 }
319 }
320 if let Some(rules) = parse_noqa_comment(text) {
321 for r in rules {
322 m.ignores.push((line, r));
323 }
324 }
325 }
326 if is_operand(kind) {
328 h_total_oprs += 1;
329 h_oprs.insert(text);
330 } else if !kind.is_trivia()
331 && !matches!(
332 kind,
333 TokenKind::Newline
334 | TokenKind::Indent
335 | TokenKind::Dedent
336 | TokenKind::EndOfFile
337 )
338 {
339 h_total_ops += 1;
340 h_ops.insert(kind);
341 }
342 }
343 m.used_names.sort();
344 m.used_names.dedup();
345 let vocab = (h_ops.len() + h_oprs.len()) as f64;
346 let length = (h_total_ops + h_total_oprs) as f64;
347 m.halstead_volume = if vocab <= 1.0 {
348 0.0
349 } else {
350 length * vocab.log2()
351 };
352
353 scan_top_level(&module.body, &li, false, &mut m);
355
356 let mut nested = NestedImportVisitor {
359 li: &li,
360 depth: 0,
361 out: Vec::new(),
362 };
363 for stmt in &module.body {
364 nested.visit_stmt(stmt);
365 }
366 m.nested_imports = nested.out;
367
368 let mut main = MainVisitor { li: &li, m: &mut m };
370 for stmt in &module.body {
371 main.visit_stmt(stmt);
372 }
373
374 let mut lu = LocalUseVisitor {
377 uses: Vec::new(),
378 attrs: Vec::new(),
379 };
380 for stmt in &module.body {
381 lu.visit_stmt(stmt);
382 }
383 lu.uses.sort();
384 lu.uses.dedup();
385 m.local_uses = lu.uses;
386 lu.attrs.sort();
387 lu.attrs.dedup();
388 m.attr_accessed = lu.attrs;
389
390 let mut res = Resolver {
393 scopes: Vec::new(),
394 used: HashSet::new(),
395 };
396 for stmt in &module.body {
397 res.visit_stmt(stmt);
398 }
399 let mut mu: Vec<String> = res.used.into_iter().collect();
400 mu.sort();
401 m.module_used = mu;
402
403 let mut defs = DefVisitor {
405 funcs: Vec::new(),
406 classes: Vec::new(),
407 };
408 for stmt in &module.body {
409 defs.visit_stmt(stmt);
410 }
411 for f in &defs.funcs {
412 m.functions.push(function_complexity(f, &li));
413 analyze_scope(f, &name_tokens, &mut m.scope_findings, &li);
414 }
415 m.functions.sort_by_key(|f| f.line);
416 m.scope_findings.sort_by_key(|s| s.line);
417 for c in &defs.classes {
418 m.classes.push(class_info(c, &li));
419 }
420 m.classes.sort_by_key(|c| c.line);
421
422 let mut ur = UnreachableVisitor {
425 li: &li,
426 out: Vec::new(),
427 };
428 ur.scan(&module.body);
429 for stmt in &module.body {
430 ur.visit_stmt(stmt);
431 }
432 ur.out.sort_by_key(|u| u.line);
433 ur.out.dedup();
434 m.unreachable = ur.out;
435
436 scan_type_leaks(&module.body, &li, &mut m.type_leaks);
438 m.type_leaks
439 .sort_by(|a, b| a.line.cmp(&b.line).then(a.type_name.cmp(&b.type_name)));
440 m.type_leaks.dedup();
441
442 security_imports(&mut m);
444 m.security_hits
445 .sort_by(|a, b| a.line.cmp(&b.line).then(a.rule.cmp(b.rule)));
446 m.security_hits
447 .dedup_by(|a, b| a.rule == b.rule && a.line == b.line);
448
449 let mut span_ignores: Vec<(u32, String)> = Vec::new();
455 for (line, rule) in &m.ignores {
456 for imp in &m.imports {
457 if *line > imp.line && *line <= imp.end_line {
458 span_ignores.push((imp.line, rule.clone()));
459 }
460 }
461 }
462 m.ignores.extend(span_ignores);
463 Ok(m)
464 }
465}
466
467const DYNAMIC_SINKS: &[&str] = &["getattr", "setattr", "eval", "exec", "__import__"];
472
473fn line1(li: &LineIndex, off: TextSize) -> u32 {
475 li.line_index(off).get() as u32
476}
477
478fn end_line1(li: &LineIndex, range: TextRange) -> u32 {
480 let end = range.end();
481 if end > range.start() {
482 line1(li, end.checked_sub(TextSize::from(1)).unwrap_or(end))
483 } else {
484 line1(li, end)
485 }
486}
487
488fn is_operand(kind: TokenKind) -> bool {
490 matches!(
491 kind,
492 TokenKind::Name
493 | TokenKind::Int
494 | TokenKind::Float
495 | TokenKind::Complex
496 | TokenKind::String
497 | TokenKind::FStringStart
498 | TokenKind::FStringMiddle
499 | TokenKind::FStringEnd
500 | TokenKind::True
501 | TokenKind::False
502 | TokenKind::None
503 )
504}
505
506fn expr_path(e: &Expr) -> Option<String> {
508 match e {
509 Expr::Name(n) => Some(n.id.as_str().to_string()),
510 Expr::Attribute(a) => Some(format!("{}.{}", expr_path(&a.value)?, a.attr.as_str())),
511 _ => None,
512 }
513}
514
515fn decorator_path(e: &Expr) -> Option<String> {
517 match e {
518 Expr::Call(c) => expr_path(&c.func),
519 other => expr_path(other),
520 }
521}
522
523fn is_private(name: &str) -> bool {
524 name.starts_with('_')
525}
526
527fn scan_top_level(stmts: &[Stmt], li: &LineIndex, type_checking: bool, m: &mut ParsedModule) {
532 for stmt in stmts {
533 match stmt {
534 Stmt::FunctionDef(f) => m.definitions.push(Definition {
535 private_by_convention: is_private(f.name.as_str()),
536 name: f.name.to_string(),
537 kind: DefKind::Function,
538 line: line1(li, f.name.range().start()),
540 end_line: end_line1(li, f.range()),
541 decorators: f
542 .decorator_list
543 .iter()
544 .filter_map(|d| decorator_path(&d.expression))
545 .collect(),
546 }),
547 Stmt::ClassDef(c) => m.definitions.push(Definition {
548 private_by_convention: is_private(c.name.as_str()),
549 name: c.name.to_string(),
550 kind: DefKind::Class,
551 line: line1(li, c.name.range().start()),
552 end_line: end_line1(li, c.range()),
553 decorators: c
554 .decorator_list
555 .iter()
556 .filter_map(|d| decorator_path(&d.expression))
557 .collect(),
558 }),
559 Stmt::Import(i) => parse_import(i, li, &mut m.imports),
560 Stmt::ImportFrom(i) => {
561 let mut imp = parse_import_from(i, li);
562 imp.type_checking_only = type_checking;
563 m.imports.push(imp);
564 }
565 Stmt::Assign(a) => {
566 if let [Expr::Name(target)] = a.targets.as_slice() {
567 let name = target.id.as_str();
568 if name == "__all__" {
569 match string_list(&a.value) {
570 Some(items) => m.dunder_all = Some(items),
571 None => m.dunder_all_dynamic = true,
573 }
574 } else {
575 m.definitions.push(Definition {
576 private_by_convention: is_private(name),
577 name: name.to_string(),
578 kind: DefKind::Variable,
579 line: line1(li, a.range().start()),
580 end_line: end_line1(li, a.range()),
581 decorators: Vec::new(),
582 });
583 }
584 }
585 }
586 Stmt::AnnAssign(a) => {
587 if let Expr::Name(target) = &*a.target {
588 let name = target.id.as_str();
589 if name == "__all__" {
590 if let Some(v) = &a.value {
591 match string_list(v) {
592 Some(items) => m.dunder_all = Some(items),
593 None => m.dunder_all_dynamic = true,
594 }
595 }
596 } else {
597 m.definitions.push(Definition {
598 private_by_convention: is_private(name),
599 name: name.to_string(),
600 kind: DefKind::Variable,
601 line: line1(li, a.range().start()),
602 end_line: end_line1(li, a.range()),
603 decorators: Vec::new(),
604 });
605 }
606 }
607 }
608 Stmt::AugAssign(a) => {
613 if let Expr::Name(t) = &*a.target {
614 if t.id.as_str() == "__all__" {
615 match string_list(&a.value) {
616 Some(items) => match &mut m.dunder_all {
617 Some(all) => all.extend(items),
618 None => m.dunder_all = Some(items),
619 },
620 None => {
621 m.dunder_all = None;
622 m.dunder_all_dynamic = true;
623 }
624 }
625 }
626 }
627 }
628 Stmt::Expr(e) => {
630 if let Expr::Call(c) = &*e.value {
631 match expr_path(&c.func).as_deref() {
632 Some("__all__.extend") => {
633 match c.arguments.args.first().and_then(string_list) {
634 Some(items) => match &mut m.dunder_all {
635 Some(all) => all.extend(items),
636 None => m.dunder_all = Some(items),
637 },
638 None => {
639 m.dunder_all = None;
640 m.dunder_all_dynamic = true;
641 }
642 }
643 }
644 Some("__all__.append") => match c.arguments.args.first() {
645 Some(Expr::StringLiteral(s)) => match &mut m.dunder_all {
646 Some(all) => all.push(s.value.to_str().to_string()),
647 None => m.dunder_all = Some(vec![s.value.to_str().to_string()]),
648 },
649 _ => {
650 m.dunder_all = None;
651 m.dunder_all_dynamic = true;
652 }
653 },
654 _ => {}
655 }
656 }
657 }
658 Stmt::If(i) => {
660 if is_main_guard(&i.test) {
661 m.has_main_guard = true;
662 }
663 let body_tc = type_checking || is_type_checking_guard(&i.test);
667 let else_tc = type_checking || is_not_type_checking_guard(&i.test);
668 let before = m.imports.len();
669 scan_top_level(&i.body, li, body_tc, m);
670 for imp in m.imports[before..].iter_mut() {
671 if body_tc {
672 imp.type_checking_only = true;
673 } else {
674 imp.in_try = true;
680 }
681 }
682 for clause in &i.elif_else_clauses {
683 let before = m.imports.len();
684 scan_top_level(&clause.body, li, else_tc, m);
685 for imp in m.imports[before..].iter_mut() {
686 if else_tc {
687 imp.type_checking_only = true;
688 } else {
689 imp.in_try = true;
690 }
691 }
692 }
693 }
694 Stmt::Try(t) => {
695 let before = m.imports.len();
700 scan_top_level(&t.body, li, type_checking, m);
701 for h in &t.handlers {
702 let ruff_python_ast::ExceptHandler::ExceptHandler(eh) = h;
703 scan_top_level(&eh.body, li, type_checking, m);
704 }
705 for imp in m.imports[before..].iter_mut() {
706 imp.in_try = true;
707 }
708 scan_top_level(&t.orelse, li, type_checking, m);
709 scan_top_level(&t.finalbody, li, type_checking, m);
710 }
711 Stmt::With(w) => scan_top_level(&w.body, li, type_checking, m),
713 Stmt::For(f) => {
714 scan_top_level(&f.body, li, type_checking, m);
715 scan_top_level(&f.orelse, li, type_checking, m);
716 }
717 Stmt::While(w) => {
718 scan_top_level(&w.body, li, type_checking, m);
719 scan_top_level(&w.orelse, li, type_checking, m);
720 }
721 Stmt::Match(mt) => {
722 for case in &mt.cases {
723 scan_top_level(&case.body, li, type_checking, m);
724 }
725 }
726 _ => {}
727 }
728 }
729}
730
731struct NestedImportVisitor<'a> {
734 li: &'a LineIndex,
735 depth: u32,
736 out: Vec<Import>,
737}
738
739impl<'a> Visitor<'a> for NestedImportVisitor<'a> {
740 fn visit_stmt(&mut self, stmt: &'a Stmt) {
741 match stmt {
742 Stmt::FunctionDef(_) | Stmt::ClassDef(_) => {
743 self.depth += 1;
744 walk_stmt(self, stmt);
745 self.depth -= 1;
746 }
747 Stmt::Import(i) if self.depth > 0 => {
748 parse_import(i, self.li, &mut self.out);
749 walk_stmt(self, stmt);
750 }
751 Stmt::ImportFrom(i) if self.depth > 0 => {
752 self.out.push(parse_import_from(i, self.li));
753 walk_stmt(self, stmt);
754 }
755 _ => walk_stmt(self, stmt),
756 }
757 }
758}
759
760fn is_main_guard(test: &Expr) -> bool {
763 let Expr::Compare(c) = test else {
764 return false;
765 };
766 let Some((left, op, right)) = c.as_single() else {
767 return false;
768 };
769 if *op != ruff_python_ast::CmpOp::Eq {
770 return false;
771 }
772 let is_name = |e: &Expr| matches!(e, Expr::Name(n) if n.id.as_str() == "__name__");
773 let is_main_str =
774 |e: &Expr| matches!(e, Expr::StringLiteral(s) if s.value.to_str() == "__main__");
775 (is_name(left) && is_main_str(right)) || (is_main_str(left) && is_name(right))
776}
777
778fn is_type_checking_guard(test: &Expr) -> bool {
781 if let Expr::BooleanLiteral(b) = test {
782 return !b.value; }
784 expr_path(test)
785 .map(|p| p == "TYPE_CHECKING" || p.ends_with(".TYPE_CHECKING"))
786 .unwrap_or(false)
787}
788
789fn is_not_type_checking_guard(test: &Expr) -> bool {
792 if let Expr::UnaryOp(u) = test {
793 return matches!(u.op, ruff_python_ast::UnaryOp::Not) && is_type_checking_guard(&u.operand);
794 }
795 false
796}
797
798fn parse_import(i: &StmtImport, li: &LineIndex, out: &mut Vec<Import>) {
799 let line = line1(li, i.range().start());
800 let end_line = end_line1(li, i.range());
801 for alias in &i.names {
802 let module = alias.name.as_str().to_string();
803 let redundant = matches!(&alias.asname, Some(a) if a.as_str() == alias.name.as_str());
804 let binding = match &alias.asname {
805 Some(a) => a.as_str().to_string(),
806 None => module.split('.').next().unwrap_or(&module).to_string(),
807 };
808 if !module.is_empty() {
809 let bindings = if binding.is_empty() {
810 vec![]
811 } else {
812 vec![binding]
813 };
814 out.push(Import {
815 module,
816 relative_dots: 0,
817 names: vec![],
818 redundant: vec![redundant; bindings.len()],
819 bindings,
820 is_star: false,
821 type_checking_only: false,
822 in_try: false,
823 line,
824 end_line,
825 });
826 }
827 }
828}
829
830fn parse_import_from(i: &StmtImportFrom, li: &LineIndex) -> Import {
831 let line = line1(li, i.range().start());
832 let end_line = end_line1(li, i.range());
833 let module = i.module.as_ref().map(|m| m.to_string()).unwrap_or_default();
834 let mut names = Vec::new();
835 let mut bindings = Vec::new();
836 let mut redundant = Vec::new();
837 let mut is_star = false;
838 for alias in &i.names {
839 let name = alias.name.as_str();
840 if name == "*" {
841 is_star = true;
842 continue;
843 }
844 names.push(name.to_string());
845 redundant.push(matches!(&alias.asname, Some(a) if a.as_str() == name));
846 bindings.push(match &alias.asname {
847 Some(a) => a.as_str().to_string(),
848 None => name.to_string(),
849 });
850 }
851 Import {
852 module,
853 relative_dots: i.level.min(u8::MAX as u32) as u8,
854 names,
855 bindings,
856 redundant,
857 is_star,
858 type_checking_only: false,
859 in_try: false,
860 line,
861 end_line,
862 }
863}
864
865fn string_list(e: &Expr) -> Option<Vec<String>> {
867 let elts = match e {
868 Expr::List(l) => &l.elts,
869 Expr::Tuple(t) => &t.elts,
870 _ => return None,
871 };
872 Some(
873 elts.iter()
874 .filter_map(|el| match el {
875 Expr::StringLiteral(s) => Some(s.value.to_str().to_string()),
876 _ => None,
877 })
878 .collect(),
879 )
880}
881
882fn function_complexity(f: &StmtFunctionDef, li: &LineIndex) -> FunctionComplexity {
887 let (params_total, params_annotated) = count_params(&f.parameters);
888 let mut cv = CycloVisitor { count: 0 };
889 for s in &f.body {
890 cv.visit_stmt(s);
891 }
892 FunctionComplexity {
893 name: f.name.to_string(),
894 line: line1(li, f.name.range().start()),
896 end_line: end_line1(li, f.range()),
897 cyclomatic: 1 + cv.count,
898 cognitive: cog_stmts(&f.body, 0),
899 params_total,
900 params_annotated,
901 return_annotated: f.returns.is_some(),
902 }
903}
904
905fn count_params(params: &Parameters) -> (u32, u32) {
906 let positional: Vec<_> = params
907 .posonlyargs
908 .iter()
909 .chain(params.args.iter())
910 .collect();
911 let mut total = 0u32;
912 let mut annotated = 0u32;
913 for (idx, p) in positional.iter().enumerate() {
914 let name = p.parameter.name.as_str();
915 if idx == 0 && (name == "self" || name == "cls") {
916 continue;
917 }
918 total += 1;
919 if p.parameter.annotation.is_some() {
920 annotated += 1;
921 }
922 }
923 for p in ¶ms.kwonlyargs {
924 total += 1;
925 if p.parameter.annotation.is_some() {
926 annotated += 1;
927 }
928 }
929 (total, annotated.min(total))
930}
931
932struct CycloVisitor {
934 count: u32,
935}
936impl<'a> Visitor<'a> for CycloVisitor {
937 fn visit_stmt(&mut self, stmt: &'a Stmt) {
938 match stmt {
939 Stmt::FunctionDef(_) | Stmt::ClassDef(_) => return, Stmt::If(i) => {
941 self.count += 1 + i
942 .elif_else_clauses
943 .iter()
944 .filter(|c| c.test.is_some())
945 .count() as u32;
946 }
947 Stmt::For(_) | Stmt::While(_) => self.count += 1,
948 Stmt::Try(t) => self.count += t.handlers.len() as u32,
949 Stmt::Assert(_) => self.count += 1,
950 Stmt::Match(mt) => self.count += mt.cases.len() as u32,
951 _ => {}
952 }
953 walk_stmt(self, stmt);
954 }
955 fn visit_expr(&mut self, expr: &'a Expr) {
956 match expr {
957 Expr::BoolOp(b) => self.count += (b.values.len() as u32).saturating_sub(1),
958 Expr::If(_) => self.count += 1, Expr::ListComp(c) => self.count += comp_points(&c.generators),
960 Expr::SetComp(c) => self.count += comp_points(&c.generators),
961 Expr::DictComp(c) => self.count += comp_points(&c.generators),
962 Expr::Generator(c) => self.count += comp_points(&c.generators),
963 _ => {}
964 }
965 walk_expr(self, expr);
966 }
967}
968
969fn comp_points(gens: &[ruff_python_ast::Comprehension]) -> u32 {
970 gens.iter().map(|g| 1 + g.ifs.len() as u32).sum()
971}
972
973fn cog_stmts(stmts: &[Stmt], nesting: u32) -> u32 {
975 stmts.iter().map(|s| cog_stmt(s, nesting)).sum()
976}
977
978fn cog_stmt(s: &Stmt, nesting: u32) -> u32 {
979 match s {
980 Stmt::FunctionDef(_) | Stmt::ClassDef(_) => 0,
981 Stmt::If(i) => {
982 let mut c = 1 + nesting + cog_cond(&i.test);
983 c += cog_stmts(&i.body, nesting + 1);
984 for clause in &i.elif_else_clauses {
985 c += 1; if let Some(t) = &clause.test {
987 c += cog_cond(t);
988 }
989 c += cog_stmts(&clause.body, nesting + 1);
990 }
991 c
992 }
993 Stmt::For(f) => {
994 1 + nesting + cog_stmts(&f.body, nesting + 1) + cog_stmts(&f.orelse, nesting + 1)
995 }
996 Stmt::While(w) => {
997 1 + nesting
998 + cog_cond(&w.test)
999 + cog_stmts(&w.body, nesting + 1)
1000 + cog_stmts(&w.orelse, nesting + 1)
1001 }
1002 Stmt::With(w) => cog_stmts(&w.body, nesting),
1003 Stmt::Try(t) => {
1004 let mut c = cog_stmts(&t.body, nesting);
1005 for h in &t.handlers {
1006 let ruff_python_ast::ExceptHandler::ExceptHandler(eh) = h;
1007 c += 1 + nesting + cog_stmts(&eh.body, nesting + 1);
1008 }
1009 c += cog_stmts(&t.orelse, nesting) + cog_stmts(&t.finalbody, nesting);
1010 c
1011 }
1012 Stmt::Match(mt) => {
1013 let mut c = 0;
1014 for case in &mt.cases {
1015 c += 1 + nesting + cog_stmts(&case.body, nesting + 1);
1016 }
1017 c
1018 }
1019 Stmt::Expr(e) => cog_cond(&e.value),
1020 Stmt::Return(r) => r.value.as_ref().map(|v| cog_cond(v)).unwrap_or(0),
1021 Stmt::Assign(a) => cog_cond(&a.value),
1022 Stmt::AugAssign(a) => cog_cond(&a.value),
1023 Stmt::AnnAssign(a) => a.value.as_ref().map(|v| cog_cond(v)).unwrap_or(0),
1024 _ => 0,
1025 }
1026}
1027
1028fn cog_cond(e: &Expr) -> u32 {
1030 let mut v = CondVisitor { count: 0 };
1031 v.visit_expr(e);
1032 v.count
1033}
1034struct CondVisitor {
1035 count: u32,
1036}
1037impl<'a> Visitor<'a> for CondVisitor {
1038 fn visit_expr(&mut self, expr: &'a Expr) {
1039 match expr {
1040 Expr::BoolOp(b) => self.count += (b.values.len() as u32).saturating_sub(1),
1041 Expr::If(_) => self.count += 1,
1042 _ => {}
1043 }
1044 walk_expr(self, expr);
1045 }
1046}
1047
1048const SCOPE_DYNAMIC: &[&str] = &["locals", "vars", "globals", "eval", "exec"];
1053
1054fn analyze_scope(
1055 f: &StmtFunctionDef,
1056 name_tokens: &[(TextSize, &str)],
1057 out: &mut Vec<ScopeFinding>,
1058 li: &LineIndex,
1059) {
1060 let range = f.range();
1062 let mut freq: HashMap<&str, u32> = HashMap::new();
1063 for (off, text) in name_tokens {
1064 if *off >= range.start() && *off < range.end() {
1065 *freq.entry(*text).or_insert(0) += 1;
1066 }
1067 }
1068 if SCOPE_DYNAMIC.iter().any(|d| freq.contains_key(*d)) {
1069 return;
1070 }
1071
1072 let mut gv = GlobalVisitor {
1074 names: HashSet::new(),
1075 };
1076 for s in &f.body {
1077 gv.visit_stmt(s);
1078 }
1079 let declared_global = gv.names;
1080
1081 let decorated = !f.decorator_list.is_empty();
1082 let fname = f.name.as_str();
1083 let is_dunder = fname.starts_with("__") && fname.ends_with("__");
1084 let stub = is_stub_body(&f.body);
1085
1086 if !decorated && !is_dunder && !stub {
1087 let positional: Vec<_> = f
1088 .parameters
1089 .posonlyargs
1090 .iter()
1091 .chain(f.parameters.args.iter())
1092 .collect();
1093 for (idx, p) in positional.iter().enumerate() {
1094 let name = p.parameter.name.as_str();
1095 if idx == 0 && (name == "self" || name == "cls") {
1096 continue;
1097 }
1098 if name.starts_with('_') || declared_global.contains(name) {
1099 continue;
1100 }
1101 if freq.get(name).copied().unwrap_or(0) == 1 {
1102 out.push(ScopeFinding {
1103 line: line1(li, p.parameter.range().start()),
1104 name: name.to_string(),
1105 is_param: true,
1106 });
1107 }
1108 }
1109 for p in &f.parameters.kwonlyargs {
1110 let name = p.parameter.name.as_str();
1111 if name.starts_with('_') || declared_global.contains(name) {
1112 continue;
1113 }
1114 if freq.get(name).copied().unwrap_or(0) == 1 {
1115 out.push(ScopeFinding {
1116 line: line1(li, p.parameter.range().start()),
1117 name: name.to_string(),
1118 is_param: true,
1119 });
1120 }
1121 }
1122 }
1123
1124 for stmt in &f.body {
1126 if let Stmt::Assign(a) = stmt {
1127 if let [Expr::Name(target)] = a.targets.as_slice() {
1128 let name = target.id.as_str();
1129 if name == "_" || declared_global.contains(name) {
1130 continue;
1131 }
1132 if freq.get(name).copied().unwrap_or(0) == 1 {
1133 out.push(ScopeFinding {
1134 line: line1(li, a.range().start()),
1135 name: name.to_string(),
1136 is_param: false,
1137 });
1138 }
1139 }
1140 }
1141 }
1142}
1143
1144struct GlobalVisitor {
1145 names: HashSet<String>,
1146}
1147impl<'a> Visitor<'a> for GlobalVisitor {
1148 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1149 match stmt {
1150 Stmt::Global(g) => {
1151 for n in &g.names {
1152 self.names.insert(n.as_str().to_string());
1153 }
1154 }
1155 Stmt::Nonlocal(g) => {
1156 for n in &g.names {
1157 self.names.insert(n.as_str().to_string());
1158 }
1159 }
1160 _ => {}
1161 }
1162 walk_stmt(self, stmt);
1163 }
1164}
1165
1166fn is_stub_body(body: &[Stmt]) -> bool {
1168 body.iter().all(|s| match s {
1169 Stmt::Pass(_) => true,
1170 Stmt::Raise(_) => true,
1171 Stmt::Expr(e) => matches!(&*e.value, Expr::StringLiteral(_) | Expr::EllipsisLiteral(_)),
1172 _ => false,
1173 })
1174}
1175
1176fn class_info(c: &StmtClassDef, li: &LineIndex) -> ClassInfo {
1181 let mut methods = Vec::new();
1182 let mut members: Vec<ClassMember> = Vec::new();
1183 for stmt in &c.body {
1184 match stmt {
1185 Stmt::FunctionDef(f) => {
1186 methods.push((f.name.to_string(), self_attrs(f)));
1187 members.push(ClassMember {
1188 name: f.name.to_string(),
1189 line: line1(li, f.name.range().start()),
1191 end_line: end_line1(li, f.range()),
1192 is_method: true,
1193 is_private: is_private(f.name.as_str()),
1194 decorators: f
1195 .decorator_list
1196 .iter()
1197 .filter_map(|d| decorator_path(&d.expression))
1198 .collect(),
1199 });
1200 }
1201 Stmt::Assign(a) => {
1202 if let [Expr::Name(t)] = a.targets.as_slice() {
1203 members.push(class_attr_member(t.id.as_str(), a.range(), li));
1204 }
1205 }
1206 Stmt::AnnAssign(a) => {
1207 if let Expr::Name(t) = &*a.target {
1208 members.push(class_attr_member(t.id.as_str(), a.range(), li));
1209 }
1210 }
1211 _ => {}
1212 }
1213 }
1214 let bases: Vec<String> = c
1215 .arguments
1216 .as_ref()
1217 .map(|args| args.args.iter().filter_map(expr_path).collect())
1218 .unwrap_or_default();
1219 let is_enum = bases.iter().any(|b| {
1220 let last = b.rsplit('.').next().unwrap_or(b);
1221 matches!(
1222 last,
1223 "Enum" | "IntEnum" | "StrEnum" | "Flag" | "IntFlag" | "ReprEnum" | "EnumMeta"
1224 )
1225 });
1226 ClassInfo {
1227 name: c.name.to_string(),
1228 line: line1(li, c.name.range().start()),
1230 end_line: end_line1(li, c.range()),
1231 is_private: is_private(c.name.as_str()),
1232 decorators: c
1233 .decorator_list
1234 .iter()
1235 .filter_map(|d| decorator_path(&d.expression))
1236 .collect(),
1237 bases,
1238 is_enum,
1239 methods,
1240 members,
1241 }
1242}
1243
1244fn class_attr_member(name: &str, range: TextRange, li: &LineIndex) -> ClassMember {
1245 ClassMember {
1246 name: name.to_string(),
1247 line: line1(li, range.start()),
1248 end_line: end_line1(li, range),
1249 is_method: false,
1250 is_private: is_private(name),
1251 decorators: Vec::new(),
1252 }
1253}
1254
1255struct UnreachableVisitor<'li> {
1260 li: &'li LineIndex,
1261 out: Vec<UnreachableCode>,
1262}
1263impl<'li> UnreachableVisitor<'li> {
1264 fn scan(&mut self, body: &[Stmt]) {
1266 for (i, stmt) in body.iter().enumerate() {
1267 if let Some(term) = terminator_kind(stmt) {
1268 if let Some(next) = body.get(i + 1) {
1269 self.out.push(UnreachableCode {
1271 line: line1(self.li, next.range().start()),
1272 after: term,
1273 });
1274 }
1275 break; }
1277 }
1278 }
1279}
1280impl<'a, 'li> Visitor<'a> for UnreachableVisitor<'li> {
1281 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1282 match stmt {
1284 Stmt::FunctionDef(f) => self.scan(&f.body),
1285 Stmt::ClassDef(c) => self.scan(&c.body),
1286 Stmt::If(i) => {
1287 self.scan(&i.body);
1288 for c in &i.elif_else_clauses {
1289 self.scan(&c.body);
1290 }
1291 }
1292 Stmt::For(f) => {
1293 self.scan(&f.body);
1294 self.scan(&f.orelse);
1295 }
1296 Stmt::While(w) => {
1297 self.scan(&w.body);
1298 self.scan(&w.orelse);
1299 }
1300 Stmt::With(w) => self.scan(&w.body),
1301 Stmt::Try(t) => {
1302 self.scan(&t.body);
1303 for h in &t.handlers {
1304 let ruff_python_ast::ExceptHandler::ExceptHandler(eh) = h;
1305 self.scan(&eh.body);
1306 }
1307 self.scan(&t.orelse);
1308 self.scan(&t.finalbody);
1309 }
1310 Stmt::Match(mt) => {
1311 for case in &mt.cases {
1312 self.scan(&case.body);
1313 }
1314 }
1315 _ => {}
1316 }
1317 walk_stmt(self, stmt);
1318 }
1319}
1320
1321fn terminator_kind(stmt: &Stmt) -> Option<&'static str> {
1323 match stmt {
1324 Stmt::Return(_) => Some("return"),
1325 Stmt::Raise(_) => Some("raise"),
1326 Stmt::Break(_) => Some("break"),
1327 Stmt::Continue(_) => Some("continue"),
1328 Stmt::Expr(e) if is_noreturn_call(&e.value) => Some("exit call"),
1329 _ => None,
1330 }
1331}
1332
1333fn is_noreturn_call(e: &Expr) -> bool {
1335 if let Expr::Call(c) = e {
1336 if let Some(p) = expr_path(&c.func) {
1337 return matches!(p.as_str(), "sys.exit" | "os._exit" | "exit" | "quit");
1340 }
1341 }
1342 false
1343}
1344
1345fn is_private_type(name: &str) -> bool {
1352 name.starts_with('_') && !(name.starts_with("__") && name.ends_with("__"))
1353}
1354
1355fn scan_type_leaks(body: &[Stmt], li: &LineIndex, out: &mut Vec<TypeLeak>) {
1356 let mut typevars: HashSet<String> = HashSet::new();
1359 collect_typevars(body, &mut typevars);
1360 for stmt in body {
1361 match stmt {
1362 Stmt::FunctionDef(f) if !is_private(f.name.as_str()) => {
1363 collect_fn_leaks(None, f, li, &typevars, out);
1364 }
1365 Stmt::ClassDef(c) if !is_private(c.name.as_str()) => {
1366 for s in &c.body {
1367 if let Stmt::FunctionDef(f) = s {
1368 if !is_private(f.name.as_str()) {
1369 collect_fn_leaks(Some(c.name.as_str()), f, li, &typevars, out);
1370 }
1371 }
1372 }
1373 }
1374 _ => {}
1375 }
1376 }
1377}
1378
1379fn collect_typevars(body: &[Stmt], out: &mut HashSet<String>) {
1382 for stmt in body {
1383 match stmt {
1384 Stmt::Assign(a) => {
1385 if let (Some(Expr::Name(t)), Expr::Call(c)) = (a.targets.first(), &*a.value) {
1386 if let Some(p) = expr_path(&c.func) {
1387 let last = p.rsplit('.').next().unwrap_or(&p);
1388 if matches!(last, "TypeVar" | "ParamSpec" | "TypeVarTuple") {
1389 out.insert(t.id.as_str().to_string());
1390 }
1391 }
1392 }
1393 }
1394 Stmt::If(i) => {
1395 collect_typevars(&i.body, out);
1396 for clause in &i.elif_else_clauses {
1397 collect_typevars(&clause.body, out);
1398 }
1399 }
1400 Stmt::Try(t) => {
1401 collect_typevars(&t.body, out);
1402 for h in &t.handlers {
1403 let ruff_python_ast::ExceptHandler::ExceptHandler(eh) = h;
1404 collect_typevars(&eh.body, out);
1405 }
1406 collect_typevars(&t.orelse, out);
1407 collect_typevars(&t.finalbody, out);
1408 }
1409 _ => {}
1410 }
1411 }
1412}
1413
1414fn collect_fn_leaks(
1415 class: Option<&str>,
1416 f: &StmtFunctionDef,
1417 li: &LineIndex,
1418 typevars: &HashSet<String>,
1419 out: &mut Vec<TypeLeak>,
1420) {
1421 let qualified = match class {
1422 Some(c) => format!("{c}.{}", f.name),
1423 None => f.name.to_string(),
1424 };
1425 let push_leaks = |ann: &Expr, line: u32, is_return: bool, out: &mut Vec<TypeLeak>| {
1426 let mut idents = Vec::new();
1427 annotation_idents(ann, &mut idents);
1428 for id in idents {
1429 if is_private_type(&id) && !typevars.contains(&id) {
1430 out.push(TypeLeak {
1431 function: qualified.clone(),
1432 type_name: id,
1433 line,
1434 is_return,
1435 });
1436 }
1437 }
1438 };
1439 for p in f
1440 .parameters
1441 .posonlyargs
1442 .iter()
1443 .chain(f.parameters.args.iter())
1444 .chain(f.parameters.kwonlyargs.iter())
1445 {
1446 if let Some(ann) = &p.parameter.annotation {
1447 push_leaks(ann, line1(li, p.parameter.range().start()), false, out);
1448 }
1449 }
1450 if let Some(r) = &f.returns {
1451 push_leaks(r, line1(li, f.name.range().start()), true, out);
1453 }
1454}
1455
1456fn annotation_idents(e: &Expr, out: &mut Vec<String>) {
1460 match e {
1461 Expr::Name(n) => out.push(n.id.as_str().to_string()),
1462 Expr::Attribute(a) => {
1463 annotation_idents(&a.value, out);
1464 out.push(a.attr.as_str().to_string());
1465 }
1466 Expr::Subscript(s) => {
1467 annotation_idents(&s.value, out);
1468 annotation_idents(&s.slice, out);
1469 }
1470 Expr::Tuple(t) => t.elts.iter().for_each(|el| annotation_idents(el, out)),
1471 Expr::List(l) => l.elts.iter().for_each(|el| annotation_idents(el, out)),
1472 Expr::BinOp(b) => {
1473 annotation_idents(&b.left, out);
1474 annotation_idents(&b.right, out);
1475 }
1476 Expr::StringLiteral(s) => {
1477 for tok in identifier_tokens(s.value.to_str()) {
1478 out.push(tok);
1479 }
1480 }
1481 _ => {}
1482 }
1483}
1484
1485fn self_attrs(f: &StmtFunctionDef) -> Vec<String> {
1486 let mut v = SelfAttrVisitor {
1487 attrs: std::collections::BTreeSet::new(),
1488 };
1489 for s in &f.body {
1490 v.visit_stmt(s);
1491 }
1492 v.attrs.into_iter().collect()
1493}
1494
1495struct SelfAttrVisitor {
1496 attrs: std::collections::BTreeSet<String>,
1497}
1498impl<'a> Visitor<'a> for SelfAttrVisitor {
1499 fn visit_expr(&mut self, expr: &'a Expr) {
1500 if let Expr::Attribute(a) = expr {
1501 if let Expr::Name(obj) = &*a.value {
1502 if obj.id.as_str() == "self" || obj.id.as_str() == "cls" {
1503 self.attrs.insert(a.attr.as_str().to_string());
1504 }
1505 }
1506 }
1507 walk_expr(self, expr);
1508 }
1509}
1510
1511struct DefVisitor<'a> {
1516 funcs: Vec<&'a StmtFunctionDef>,
1517 classes: Vec<&'a StmtClassDef>,
1518}
1519impl<'a> Visitor<'a> for DefVisitor<'a> {
1520 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1521 match stmt {
1522 Stmt::FunctionDef(f) => self.funcs.push(f),
1523 Stmt::ClassDef(c) => self.classes.push(c),
1524 _ => {}
1525 }
1526 walk_stmt(self, stmt);
1527 }
1528}
1529
1530struct LocalUseVisitor {
1535 uses: Vec<String>,
1536 attrs: Vec<String>,
1538}
1539impl<'a> Visitor<'a> for LocalUseVisitor {
1540 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1541 if matches!(stmt, Stmt::Import(_) | Stmt::ImportFrom(_)) {
1543 return;
1544 }
1545 if let Stmt::AnnAssign(a) = stmt {
1547 collect_annotation_strings(&a.annotation, &mut self.uses);
1548 if is_type_alias_annotation(&a.annotation) {
1554 if let Some(v) = &a.value {
1555 collect_annotation_strings(v, &mut self.uses);
1556 }
1557 }
1558 }
1559 if let Stmt::FunctionDef(f) = stmt {
1560 if let Some(r) = &f.returns {
1561 collect_annotation_strings(r, &mut self.uses);
1562 }
1563 for p in f
1564 .parameters
1565 .posonlyargs
1566 .iter()
1567 .chain(f.parameters.args.iter())
1568 .chain(f.parameters.kwonlyargs.iter())
1569 {
1570 if let Some(ann) = &p.parameter.annotation {
1571 collect_annotation_strings(ann, &mut self.uses);
1572 }
1573 }
1574 }
1575 walk_stmt(self, stmt);
1576 }
1577 fn visit_expr(&mut self, expr: &'a Expr) {
1578 match expr {
1579 Expr::Name(n) => self.uses.push(n.id.as_str().to_string()),
1580 Expr::Attribute(a) => {
1581 self.uses.push(a.attr.as_str().to_string());
1582 self.attrs.push(a.attr.as_str().to_string());
1583 }
1584 Expr::Call(c) => {
1588 let is_cast = expr_path(&c.func)
1589 .map(|p| p == "cast" || p.ends_with(".cast"))
1590 .unwrap_or(false);
1591 if is_cast {
1592 if let Some(first) = c.arguments.args.first() {
1593 collect_annotation_strings(first, &mut self.uses);
1594 }
1595 }
1596 }
1597 _ => {}
1598 }
1599 walk_expr(self, expr);
1600 }
1601}
1602
1603fn is_type_alias_annotation(e: &Expr) -> bool {
1606 expr_path(e)
1607 .map(|p| p == "TypeAlias" || p.ends_with(".TypeAlias"))
1608 .unwrap_or(false)
1609}
1610
1611fn collect_annotation_strings(e: &Expr, out: &mut Vec<String>) {
1614 match e {
1615 Expr::StringLiteral(s) => {
1616 for tok in identifier_tokens(s.value.to_str()) {
1617 out.push(tok);
1618 }
1619 }
1620 Expr::Subscript(s) => {
1621 collect_annotation_strings(&s.value, out);
1622 collect_annotation_strings(&s.slice, out);
1623 }
1624 Expr::Tuple(t) => {
1625 for el in &t.elts {
1626 collect_annotation_strings(el, out);
1627 }
1628 }
1629 Expr::List(l) => {
1630 for el in &l.elts {
1631 collect_annotation_strings(el, out);
1632 }
1633 }
1634 Expr::BinOp(b) => {
1635 collect_annotation_strings(&b.left, out);
1636 collect_annotation_strings(&b.right, out);
1637 }
1638 _ => {}
1639 }
1640}
1641
1642fn identifier_tokens(s: &str) -> Vec<String> {
1643 let mut out = Vec::new();
1644 let mut cur = String::new();
1645 let flush = |cur: &mut String, out: &mut Vec<String>| {
1646 if !cur.is_empty() && !cur.chars().next().unwrap().is_ascii_digit() {
1647 out.push(std::mem::take(cur));
1648 } else {
1649 cur.clear();
1650 }
1651 };
1652 for ch in s.chars() {
1653 if ch.is_ascii_alphanumeric() || ch == '_' {
1654 cur.push(ch);
1655 } else {
1656 flush(&mut cur, &mut out);
1657 }
1658 }
1659 flush(&mut cur, &mut out);
1660 out
1661}
1662
1663struct FnScope {
1676 locals: HashSet<String>,
1677 globals: HashSet<String>,
1678}
1679
1680struct Resolver {
1681 scopes: Vec<FnScope>,
1682 used: HashSet<String>,
1683}
1684
1685impl Resolver {
1686 fn resolve_load(&mut self, name: &str) {
1687 for s in self.scopes.iter().rev() {
1688 if s.globals.contains(name) {
1689 self.used.insert(name.to_string()); return;
1691 }
1692 if s.locals.contains(name) {
1693 return; }
1695 }
1696 self.used.insert(name.to_string());
1698 }
1699
1700 fn enter_function(&mut self, f: &StmtFunctionDef) {
1701 let mut bv = BindingVisitor {
1702 locals: HashSet::new(),
1703 globals: HashSet::new(),
1704 };
1705 for p in param_names(&f.parameters) {
1706 bv.locals.insert(p);
1707 }
1708 for stmt in &f.body {
1709 bv.visit_stmt(stmt);
1710 }
1711 for g in &bv.globals {
1713 bv.locals.remove(g);
1714 }
1715 self.scopes.push(FnScope {
1716 locals: bv.locals,
1717 globals: bv.globals,
1718 });
1719 }
1720
1721 fn visit_signature_exprs(&mut self, params: &Parameters) {
1724 for p in params
1725 .posonlyargs
1726 .iter()
1727 .chain(params.args.iter())
1728 .chain(params.kwonlyargs.iter())
1729 {
1730 if let Some(d) = &p.default {
1731 self.visit_expr(d);
1732 }
1733 if let Some(a) = &p.parameter.annotation {
1734 self.visit_expr(a);
1735 }
1736 }
1737 if let Some(v) = ¶ms.vararg {
1738 if let Some(a) = &v.annotation {
1739 self.visit_expr(a);
1740 }
1741 }
1742 if let Some(k) = ¶ms.kwarg {
1743 if let Some(a) = &k.annotation {
1744 self.visit_expr(a);
1745 }
1746 }
1747 }
1748}
1749
1750impl<'a> Visitor<'a> for Resolver {
1751 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1752 match stmt {
1753 Stmt::FunctionDef(f) => {
1754 for d in &f.decorator_list {
1757 self.visit_expr(&d.expression);
1758 }
1759 self.visit_signature_exprs(&f.parameters);
1760 if let Some(r) = &f.returns {
1761 self.visit_expr(r);
1762 }
1763 self.enter_function(f);
1764 for stmt in &f.body {
1765 self.visit_stmt(stmt);
1766 }
1767 self.scopes.pop();
1768 }
1769 Stmt::ClassDef(c) => {
1770 for d in &c.decorator_list {
1771 self.visit_expr(&d.expression);
1772 }
1773 if let Some(args) = &c.arguments {
1774 for a in args.args.iter() {
1775 self.visit_expr(a);
1776 }
1777 for kw in args.keywords.iter() {
1778 self.visit_expr(&kw.value);
1779 }
1780 }
1781 for stmt in &c.body {
1783 self.visit_stmt(stmt);
1784 }
1785 }
1786 _ => walk_stmt(self, stmt),
1787 }
1788 }
1789
1790 fn visit_expr(&mut self, expr: &'a Expr) {
1791 match expr {
1792 Expr::Name(n) => {
1793 if matches!(n.ctx, ExprContext::Load) {
1794 self.resolve_load(n.id.as_str());
1795 }
1796 }
1797 Expr::Lambda(l) => {
1798 let mut locals = HashSet::new();
1799 if let Some(params) = &l.parameters {
1800 self.visit_signature_exprs(params);
1802 for p in param_names(params) {
1803 locals.insert(p);
1804 }
1805 }
1806 self.scopes.push(FnScope {
1807 locals,
1808 globals: HashSet::new(),
1809 });
1810 self.visit_expr(&l.body);
1811 self.scopes.pop();
1812 }
1813 _ => walk_expr(self, expr),
1814 }
1815 }
1816}
1817
1818struct BindingVisitor {
1822 locals: HashSet<String>,
1823 globals: HashSet<String>,
1824}
1825impl<'a> Visitor<'a> for BindingVisitor {
1826 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1827 match stmt {
1828 Stmt::FunctionDef(f) => {
1829 self.locals.insert(f.name.to_string());
1830 }
1831 Stmt::ClassDef(c) => {
1832 self.locals.insert(c.name.to_string());
1833 }
1834 Stmt::Global(g) => {
1835 for n in &g.names {
1836 self.globals.insert(n.to_string());
1837 }
1838 }
1839 Stmt::Nonlocal(g) => {
1840 for n in &g.names {
1841 self.locals.insert(n.to_string());
1843 }
1844 }
1845 _ => walk_stmt(self, stmt),
1846 }
1847 }
1848 fn visit_expr(&mut self, expr: &'a Expr) {
1849 match expr {
1850 Expr::Name(n) if matches!(n.ctx, ExprContext::Store) => {
1851 self.locals.insert(n.id.as_str().to_string());
1852 }
1853 Expr::Lambda(_)
1858 | Expr::ListComp(_)
1859 | Expr::SetComp(_)
1860 | Expr::DictComp(_)
1861 | Expr::Generator(_) => {}
1862 _ => walk_expr(self, expr),
1863 }
1864 }
1865}
1866
1867fn param_names(params: &Parameters) -> Vec<String> {
1868 let mut out = Vec::new();
1869 for p in params
1870 .posonlyargs
1871 .iter()
1872 .chain(params.args.iter())
1873 .chain(params.kwonlyargs.iter())
1874 {
1875 out.push(p.parameter.name.as_str().to_string());
1876 }
1877 if let Some(v) = ¶ms.vararg {
1878 out.push(v.name.as_str().to_string());
1879 }
1880 if let Some(k) = ¶ms.kwarg {
1881 out.push(k.name.as_str().to_string());
1882 }
1883 out
1884}
1885
1886struct MainVisitor<'a, 'm> {
1891 li: &'a LineIndex,
1892 m: &'m mut ParsedModule,
1893}
1894impl<'a, 'm> Visitor<'a> for MainVisitor<'a, 'm> {
1895 fn visit_stmt(&mut self, stmt: &'a Stmt) {
1896 match stmt {
1897 Stmt::Assign(a) => {
1898 if let [Expr::Name(t)] = a.targets.as_slice() {
1899 security_secret(t.id.as_str(), &a.value, a.range(), self.li, self.m);
1900 }
1901 }
1902 Stmt::AnnAssign(a) => {
1903 if let (Expr::Name(t), Some(v)) = (&*a.target, &a.value) {
1904 security_secret(t.id.as_str(), v, a.range(), self.li, self.m);
1905 }
1906 }
1907 Stmt::Try(t) => {
1908 for h in &t.handlers {
1911 let ruff_python_ast::ExceptHandler::ExceptHandler(eh) = h;
1912 let broad = match &eh.type_ {
1913 None => true,
1914 Some(ty) => expr_path(ty)
1915 .map(|p| {
1916 matches!(
1917 p.rsplit('.').next().unwrap_or(&p),
1918 "Exception" | "BaseException"
1919 )
1920 })
1921 .unwrap_or(false),
1922 };
1923 if broad && eh.body.iter().all(|s| matches!(s, Stmt::Pass(_))) {
1924 self.m.security_hits.push(SecurityHit {
1925 rule: "try-except-pass",
1926 line: line1(self.li, eh.range().start()),
1927 detail:
1928 "broad `except: pass` silently swallows errors; log or handle them"
1929 .into(),
1930 });
1931 }
1932 }
1933 }
1934 _ => {}
1935 }
1936 walk_stmt(self, stmt);
1937 }
1938 fn visit_expr(&mut self, expr: &'a Expr) {
1939 if let Expr::Call(c) = expr {
1940 let callee = expr_path(&c.func).unwrap_or_default();
1941 if !callee.is_empty() {
1942 if DYNAMIC_SINKS.contains(&callee.as_str()) || callee.starts_with("importlib") {
1943 self.m.has_dynamic_sink = true;
1944 }
1945 self.m.calls.push(CallSite {
1946 callee: callee.clone(),
1947 line: line1(self.li, c.func.range().start()),
1948 });
1949 }
1950 security_call(c, &callee, line1(self.li, c.range().start()), self.m);
1951 }
1952 walk_expr(self, expr);
1953 }
1954}
1955
1956const SECRET_NAMES: &[&str] = &[
1957 "password",
1958 "passwd",
1959 "secret",
1960 "token",
1961 "api_key",
1962 "apikey",
1963 "access_key",
1964 "secret_key",
1965 "private_key",
1966 "auth_token",
1967];
1968
1969fn security_secret(
1970 name: &str,
1971 value: &Expr,
1972 range: TextRange,
1973 li: &LineIndex,
1974 m: &mut ParsedModule,
1975) {
1976 let lname = name.to_ascii_lowercase();
1977 if !SECRET_NAMES.iter().any(|s| lname.contains(s)) {
1978 return;
1979 }
1980 if let Expr::StringLiteral(s) = value {
1981 let val = s.value.to_str();
1982 if val.len() >= 4 && !val.contains("${") && !val.eq_ignore_ascii_case("changeme") {
1983 m.security_hits.push(SecurityHit {
1984 rule: "hardcoded-secret",
1985 line: line1(li, range.start()),
1986 detail: format!("`{name}` assigned a hardcoded string literal"),
1987 });
1988 }
1989 }
1990}
1991
1992const WEAK_CIPHERS: &[&str] = &[
1993 "DES",
1994 "DES3",
1995 "TripleDES",
1996 "ARC2",
1997 "RC2",
1998 "ARC4",
1999 "RC4",
2000 "Blowfish",
2001 "IDEA",
2002 "CAST",
2003 "XOR",
2004];
2005
2006fn kwarg_bool(c: &ruff_python_ast::ExprCall, name: &str, want: bool) -> bool {
2007 c.arguments
2008 .find_keyword(name)
2009 .map(|kw| matches!(&kw.value, Expr::BooleanLiteral(b) if b.value == want))
2010 .unwrap_or(false)
2011}
2012
2013fn has_kwarg(c: &ruff_python_ast::ExprCall, name: &str) -> bool {
2014 c.arguments.find_keyword(name).is_some()
2015}
2016
2017fn first_positional_is_string(c: &ruff_python_ast::ExprCall) -> bool {
2018 matches!(c.arguments.args.first(), Some(Expr::StringLiteral(_)))
2019}
2020
2021fn is_dynamic_string(arg: &Expr) -> bool {
2022 match arg {
2023 Expr::FString(_) => true,
2024 Expr::BinOp(_) => true,
2025 Expr::Call(c) => expr_path(&c.func)
2026 .map(|p| p.ends_with(".format"))
2027 .unwrap_or(false),
2028 _ => false,
2029 }
2030}
2031
2032fn args_reference_ecb(c: &ruff_python_ast::ExprCall) -> bool {
2034 let refs = |e: &Expr| {
2035 expr_path(e)
2036 .map(|p| p.contains("MODE_ECB"))
2037 .unwrap_or(false)
2038 };
2039 c.arguments.args.iter().any(refs) || c.arguments.keywords.iter().any(|k| refs(&k.value))
2040}
2041
2042fn security_call(c: &ruff_python_ast::ExprCall, f: &str, line: u32, m: &mut ParsedModule) {
2043 let last = f.rsplit('.').next().unwrap_or(f);
2044 let mut hit = |rule: &'static str, detail: String| {
2045 m.security_hits.push(SecurityHit { rule, line, detail });
2046 };
2047
2048 if matches!(
2052 f,
2053 "eval" | "exec" | "compile" | "builtins.eval" | "builtins.exec" | "builtins.compile"
2054 ) && !first_positional_is_string(c)
2055 {
2056 hit(
2057 "dangerous-eval",
2058 format!("`{f}` on a non-literal expression executes dynamic code"),
2059 );
2060 }
2061 if f == "yaml.load" && !has_kwarg(c, "Loader") {
2062 hit(
2063 "unsafe-yaml-load",
2064 "yaml.load without an explicit Loader= is unsafe; use yaml.safe_load".into(),
2065 );
2066 }
2067 if matches!(
2068 f,
2069 "pickle.load"
2070 | "pickle.loads"
2071 | "cPickle.load"
2072 | "cPickle.loads"
2073 | "marshal.load"
2074 | "marshal.loads"
2075 | "dill.load"
2076 | "dill.loads"
2077 | "shelve.open"
2078 | "jsonpickle.decode"
2079 ) {
2080 hit(
2081 "unsafe-deserialization",
2082 format!("`{f}` can execute arbitrary code on untrusted input"),
2083 );
2084 }
2085 if matches!(
2086 last,
2087 "call" | "run" | "Popen" | "check_output" | "check_call"
2088 ) && kwarg_bool(c, "shell", true)
2089 {
2090 hit(
2091 "subprocess-shell-true",
2092 "subprocess call with shell=True risks shell injection".into(),
2093 );
2094 }
2095 if matches!(f, "os.system" | "os.popen" | "os.popen2" | "os.popen3") {
2096 hit(
2097 "subprocess-shell-true",
2098 format!("`{f}` runs a command through the shell; prefer subprocess with an argv list"),
2099 );
2100 }
2101 if kwarg_bool(c, "verify", false) {
2102 hit(
2103 "tls-verify-disabled",
2104 "TLS certificate verification disabled (verify=False)".into(),
2105 );
2106 }
2107 if f == "ssl._create_unverified_context" {
2108 hit(
2109 "tls-verify-disabled",
2110 "ssl._create_unverified_context disables certificate validation".into(),
2111 );
2112 }
2113 if matches!(f, "hashlib.md5" | "hashlib.sha1" | "md5.new") {
2114 hit(
2115 "weak-hash",
2116 format!("`{f}` is a weak hash; use sha256+ (or pass usedforsecurity=False)"),
2117 );
2118 }
2119 if WEAK_CIPHERS.contains(&last) {
2120 hit(
2121 "weak-cipher",
2122 format!("`{f}` is a broken/weak cipher; use AES-GCM or ChaCha20-Poly1305"),
2123 );
2124 }
2125 if args_reference_ecb(c) {
2126 hit(
2127 "weak-cipher",
2128 "ECB mode leaks plaintext structure; use an authenticated mode (GCM)".into(),
2129 );
2130 }
2131 if matches!(
2132 f,
2133 "random.random"
2134 | "random.randint"
2135 | "random.randrange"
2136 | "random.choice"
2137 | "random.getrandbits"
2138 ) {
2139 hit(
2140 "insecure-random",
2141 format!("`{f}` is not cryptographically secure; use the `secrets` module for tokens"),
2142 );
2143 }
2144 if matches!(
2145 last,
2146 "execute" | "executemany" | "executescript" | "raw" | "extra"
2147 ) {
2148 if let Some(arg) = c.arguments.args.first() {
2149 if is_dynamic_string(arg) {
2150 hit(
2151 "sql-injection",
2152 format!(
2153 "`{last}(...)` builds SQL from a dynamic string; use parameterized queries"
2154 ),
2155 );
2156 }
2157 }
2158 }
2159 if matches!(
2160 f,
2161 "requests.get"
2162 | "requests.post"
2163 | "requests.put"
2164 | "requests.delete"
2165 | "requests.patch"
2166 | "requests.head"
2167 | "requests.request"
2168 ) && !has_kwarg(c, "timeout")
2169 {
2170 hit(
2171 "request-without-timeout",
2172 format!("`{f}` without a timeout= can block indefinitely"),
2173 );
2174 }
2175 if last == "run" && kwarg_bool(c, "debug", true) {
2178 hit(
2179 "flask-debug-true",
2180 "running a web app with debug=True exposes the interactive debugger".into(),
2181 );
2182 }
2183 if last == "Environment" && kwarg_bool(c, "autoescape", false) {
2186 hit(
2187 "jinja2-autoescape-false",
2188 "Jinja2 Environment with autoescape=False risks XSS; enable autoescaping".into(),
2189 );
2190 }
2191}
2192
2193fn security_imports(m: &mut ParsedModule) {
2194 let mut hits: Vec<SecurityHit> = Vec::new();
2195 for imp in m.imports.iter().chain(m.nested_imports.iter()) {
2196 let from_crypto = imp.module.contains("Crypto") || imp.module.contains("cryptography");
2197 if !from_crypto {
2198 continue;
2199 }
2200 for name in &imp.names {
2201 if WEAK_CIPHERS.contains(&name.as_str()) {
2202 hits.push(SecurityHit {
2203 rule: "weak-cipher",
2204 line: imp.line,
2205 detail: format!(
2206 "`{name}` (imported from `{}`) is a broken/weak cipher; use AES-GCM or ChaCha20-Poly1305",
2207 imp.module
2208 ),
2209 });
2210 }
2211 }
2212 if imp.names.is_empty() {
2213 if let Some(seg) = imp.module.rsplit('.').next() {
2214 if WEAK_CIPHERS.contains(&seg) {
2215 hits.push(SecurityHit {
2216 rule: "weak-cipher",
2217 line: imp.line,
2218 detail: format!(
2219 "`{}` is a broken/weak cipher; use AES-GCM or ChaCha20-Poly1305",
2220 imp.module
2221 ),
2222 });
2223 }
2224 }
2225 }
2226 }
2227 m.security_hits.extend(hits);
2228}
2229
2230fn parse_noqa_comment(text: &str) -> Option<Vec<String>> {
2239 let t = text.trim_start_matches('#').trim();
2240 if t.len() < 4 || !t.is_char_boundary(4) || !t[..4].eq_ignore_ascii_case("noqa") {
2241 return None;
2242 }
2243 let rest = t[4..].trim_start();
2244 if rest.is_empty() || rest.starts_with('#') {
2245 return Some(vec!["unused-import".into(), "unused-variable".into()]);
2246 }
2247 let codes = rest.strip_prefix(':')?;
2248 let mut rules = Vec::new();
2249 for code in codes.split([',', ' ', '#']).map(str::trim) {
2250 match code.to_ascii_uppercase().as_str() {
2251 "F401" => rules.push("unused-import".to_string()),
2252 "F841" => rules.push("unused-variable".to_string()),
2253 _ => {}
2254 }
2255 }
2256 if rules.is_empty() {
2257 None
2258 } else {
2259 Some(rules)
2260 }
2261}
2262
2263fn parse_ignore_comment(text: &str) -> Option<Vec<String>> {
2264 let t = text.trim_start_matches('#').trim();
2265 let rest = t.strip_prefix("mollify:")?.trim();
2266 let rest = rest.strip_prefix("ignore")?.trim();
2267 if let Some(inner) = rest
2268 .strip_prefix('[')
2269 .and_then(|r| r.find(']').map(|i| &r[..i]))
2270 {
2271 let rules: Vec<String> = inner
2272 .split(',')
2273 .map(|s| s.trim().to_string())
2274 .filter(|s| !s.is_empty())
2275 .collect();
2276 if rules.is_empty() {
2277 Some(vec!["*".into()])
2278 } else {
2279 Some(rules)
2280 }
2281 } else if rest.is_empty() {
2282 Some(vec!["*".into()])
2283 } else {
2284 None
2285 }
2286}
2287
2288#[cfg(test)]
2289mod tests {
2290 use super::*;
2291
2292 fn parse(src: &str) -> ParsedModule {
2293 let mut p = PyParser::new().unwrap();
2294 p.parse(Utf8Path::new("m.py"), src).unwrap()
2295 }
2296
2297 #[test]
2298 fn extracts_functions_and_classes() {
2299 let m = parse("def foo():\n pass\n\nclass Bar:\n pass\n");
2300 let names: Vec<_> = m.definitions.iter().map(|d| d.name.as_str()).collect();
2301 assert!(names.contains(&"foo"));
2302 assert!(names.contains(&"Bar"));
2303 }
2304
2305 #[test]
2306 fn private_convention_detected() {
2307 let m = parse("def _helper():\n pass\n");
2308 assert!(m.definitions[0].private_by_convention);
2309 }
2310
2311 #[test]
2312 fn detects_expanded_security_rules() {
2313 let m = parse(
2314 "app.run(debug=True)\nenv = Environment(autoescape=False)\ntry:\n risky()\nexcept Exception:\n pass\n",
2315 );
2316 let rules: Vec<_> = m.security_hits.iter().map(|h| h.rule).collect();
2317 assert!(rules.contains(&"flask-debug-true"), "got {rules:?}");
2318 assert!(rules.contains(&"jinja2-autoescape-false"), "got {rules:?}");
2319 assert!(rules.contains(&"try-except-pass"), "got {rules:?}");
2320 let narrow = parse("try:\n x()\nexcept ValueError:\n pass\n");
2322 assert!(!narrow
2323 .security_hits
2324 .iter()
2325 .any(|h| h.rule == "try-except-pass"));
2326 }
2327
2328 #[test]
2329 fn extracts_imports() {
2330 let m = parse("import os\nfrom a.b import c, d\nfrom . import e\nfrom x import *\n");
2331 assert!(m.imports.iter().any(|i| i.module == "os"));
2332 let frm = m.imports.iter().find(|i| i.module == "a.b").unwrap();
2333 assert_eq!(frm.names, vec!["c", "d"]);
2334 assert!(m.imports.iter().any(|i| i.relative_dots == 1));
2335 assert!(m.imports.iter().any(|i| i.is_star));
2336 }
2337
2338 #[test]
2339 fn extracts_dunder_all() {
2340 let m = parse("__all__ = ['foo', 'bar']\n");
2341 assert_eq!(m.dunder_all, Some(vec!["foo".into(), "bar".into()]));
2342 }
2343
2344 #[test]
2345 fn detects_security_candidates() {
2346 let m = parse("import subprocess\npassword = \"hunter2xyz\"\nsubprocess.run(cmd, shell=True)\neval(user_input)\n");
2347 let rules: Vec<_> = m.security_hits.iter().map(|h| h.rule).collect();
2348 assert!(rules.contains(&"hardcoded-secret"), "got {rules:?}");
2349 assert!(rules.contains(&"subprocess-shell-true"), "got {rules:?}");
2350 assert!(rules.contains(&"dangerous-eval"), "got {rules:?}");
2351 let ok = parse("eval(\"1+1\")\n");
2352 assert!(!ok.security_hits.iter().any(|h| h.rule == "dangerous-eval"));
2353 }
2354
2355 #[test]
2356 fn dangerous_eval_only_matches_builtins_not_methods() {
2357 for src in [
2360 "session.exec(select(Item))\n",
2361 "conn.exec(query)\n",
2362 "obj.eval(expr)\n",
2363 "db.compile(stmt)\n",
2364 ] {
2365 let m = parse(src);
2366 assert!(
2367 !m.security_hits.iter().any(|h| h.rule == "dangerous-eval"),
2368 "method call wrongly flagged: {src}"
2369 );
2370 }
2371 for src in [
2373 "exec(code)\n",
2374 "eval(user_input)\n",
2375 "compile(src, '<s>', 'exec')\n",
2376 ] {
2377 let m = parse(src);
2378 assert!(
2379 m.security_hits.iter().any(|h| h.rule == "dangerous-eval"),
2380 "builtin not flagged: {src}"
2381 );
2382 }
2383 }
2384
2385 #[test]
2386 fn detects_weak_cipher_imports() {
2387 let m = parse(
2388 "from Crypto.Cipher import DES as pycrypto_des\n\
2389 from Cryptodome.Cipher import ARC4 as ax\n\
2390 cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR)\n\
2391 c2 = ax.new(key)\n",
2392 );
2393 let cipher_hits: Vec<_> = m
2394 .security_hits
2395 .iter()
2396 .filter(|h| h.rule == "weak-cipher")
2397 .collect();
2398 assert_eq!(
2399 cipher_hits.len(),
2400 2,
2401 "expected DES + ARC4 imports flagged, got {:?}",
2402 m.security_hits
2403 );
2404 let lines: Vec<u32> = cipher_hits.iter().map(|h| h.line).collect();
2405 assert!(lines.contains(&1) && lines.contains(&2), "lines {lines:?}");
2406 }
2407
2408 #[test]
2409 fn detects_weak_cipher_direct_constructor_and_ecb() {
2410 let m = parse(
2411 "from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher\n\
2412 c = Cipher(algorithms.ARC4(key), mode=None)\n",
2413 );
2414 assert!(
2415 m.security_hits.iter().any(|h| h.rule == "weak-cipher"),
2416 "expected ARC4 constructor flagged, got {:?}",
2417 m.security_hits
2418 );
2419 let ecb = parse("from Crypto.Cipher import AES\nc = AES.new(key, AES.MODE_ECB)\n");
2420 assert!(
2421 ecb.security_hits.iter().any(|h| h.rule == "weak-cipher"),
2422 "expected ECB mode flagged, got {:?}",
2423 ecb.security_hits
2424 );
2425 }
2426
2427 #[test]
2428 fn strong_cipher_and_modes_not_flagged() {
2429 let m = parse(
2430 "from cryptography.hazmat.primitives.ciphers import algorithms, modes, Cipher\n\
2431 c = Cipher(algorithms.AES(key), modes.GCM(iv))\n",
2432 );
2433 assert!(
2434 !m.security_hits.iter().any(|h| h.rule == "weak-cipher"),
2435 "AES-GCM should not be flagged, got {:?}",
2436 m.security_hits
2437 );
2438 let unrelated = parse("from myapp.utils import DES\nDES.do_thing()\n");
2439 assert!(
2440 !unrelated
2441 .security_hits
2442 .iter()
2443 .any(|h| h.rule == "weak-cipher"),
2444 "non-crypto `DES` import should not be flagged, got {:?}",
2445 unrelated.security_hits
2446 );
2447 }
2448
2449 #[test]
2450 fn counts_type_annotations() {
2451 let m = parse("def f(a: int, b) -> int:\n return a\n\nclass C:\n def m(self, x: int):\n return x\n");
2452 let f = m.functions.iter().find(|f| f.name == "f").unwrap();
2453 assert_eq!(f.params_total, 2);
2454 assert_eq!(f.params_annotated, 1);
2455 assert!(f.return_annotated);
2456 let mm = m.functions.iter().find(|f| f.name == "m").unwrap();
2457 assert_eq!(mm.params_total, 1, "self should be excluded");
2458 assert_eq!(mm.params_annotated, 1);
2459 assert!(!mm.return_annotated);
2460 }
2461
2462 #[test]
2463 fn computes_complexity() {
2464 let m = parse("def f(x):\n if x:\n for i in range(x):\n if i and x:\n return i\n return 0\n");
2465 let f = m.functions.iter().find(|f| f.name == "f").unwrap();
2466 assert!(f.cyclomatic >= 4, "cyclo {:?}", f.cyclomatic);
2467 assert!(f.cognitive >= 3, "cog {:?}", f.cognitive);
2468 }
2469
2470 #[test]
2471 fn captures_decorators() {
2472 let m = parse("import app\n@app.route('/x')\ndef view():\n return 1\n");
2473 let d = m.definitions.iter().find(|d| d.name == "view").unwrap();
2474 assert!(
2475 d.decorators.iter().any(|x| x == "app.route"),
2476 "got {:?}",
2477 d.decorators
2478 );
2479 }
2480
2481 #[test]
2482 fn detects_dynamic_sink() {
2483 let m = parse("x = getattr(obj, 'attr')\n");
2484 assert!(m.has_dynamic_sink);
2485 let m2 = parse("y = 1 + 2\n");
2486 assert!(!m2.has_dynamic_sink);
2487 }
2488
2489 #[test]
2490 fn conditional_import_seen() {
2491 let m = parse("try:\n import fast\nexcept ImportError:\n import slow as fast\n");
2492 assert!(m.imports.iter().any(|i| i.module == "fast"));
2493 }
2494
2495 #[test]
2496 fn scope_resolution_excludes_shadows_and_attributes() {
2497 let m = parse(
2502 "def helper():\n pass\n\ndef f():\n helper = 1\n return helper\n\nobj.helper()\n",
2503 );
2504 assert!(
2505 !m.module_used.iter().any(|s| s == "helper"),
2506 "module_used should exclude shadowed/attribute `helper`: {:?}",
2507 m.module_used
2508 );
2509 let m2 = parse("def g():\n pass\n\ng()\n");
2511 assert!(
2512 m2.module_used.iter().any(|s| s == "g"),
2513 "{:?}",
2514 m2.module_used
2515 );
2516 let m3 =
2519 parse("counter = 0\n\ndef bump():\n global counter\n counter = counter + 1\n");
2520 assert!(
2521 m3.module_used.iter().any(|s| s == "counter"),
2522 "{:?}",
2523 m3.module_used
2524 );
2525 let m4 = parse("counter = 0\n\ndef bump():\n counter = counter + 1\n");
2527 assert!(
2528 !m4.module_used.iter().any(|s| s == "counter"),
2529 "{:?}",
2530 m4.module_used
2531 );
2532 }
2533
2534 #[test]
2535 fn scope_resolution_sees_defaults_and_annotations() {
2536 let m = parse("DEFAULT = 5\nMyType = int\ndef f(x=DEFAULT) -> MyType: ...\n");
2539 assert!(
2540 m.module_used.iter().any(|s| s == "DEFAULT"),
2541 "{:?}",
2542 m.module_used
2543 );
2544 assert!(
2545 m.module_used.iter().any(|s| s == "MyType"),
2546 "{:?}",
2547 m.module_used
2548 );
2549 let m2 = parse("MyType = int\ndef g(x: MyType): ...\n");
2550 assert!(
2551 m2.module_used.iter().any(|s| s == "MyType"),
2552 "{:?}",
2553 m2.module_used
2554 );
2555 let m3 = parse("DEFAULT = 5\ng = lambda x=DEFAULT: x\n");
2557 assert!(
2558 m3.module_used.iter().any(|s| s == "DEFAULT"),
2559 "{:?}",
2560 m3.module_used
2561 );
2562 }
2563
2564 #[test]
2565 fn imports_inside_module_level_suites_seen() {
2566 let m = parse(
2567 "from contextlib import suppress\n\
2568 with suppress(ImportError):\n import ujson\n\
2569 for _i in range(1):\n import for_mod\n\
2570 while cond():\n import while_mod\n\
2571 match val:\n case 1:\n import match_mod\n",
2572 );
2573 for want in ["ujson", "for_mod", "while_mod", "match_mod"] {
2574 assert!(
2575 m.imports.iter().any(|i| i.module == want),
2576 "missing {want}: {:?}",
2577 m.imports
2578 );
2579 }
2580 }
2581
2582 #[test]
2583 fn type_checking_marks_body_not_else() {
2584 let m = parse(
2585 "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\nelse:\n import b\n",
2586 );
2587 let a = m.imports.iter().find(|i| i.module == "a").unwrap();
2588 let b = m.imports.iter().find(|i| i.module == "b").unwrap();
2589 assert!(a.type_checking_only);
2590 assert!(!b.type_checking_only, "else branch is the runtime branch");
2591 let m2 = parse(
2593 "from typing import TYPE_CHECKING\nif not TYPE_CHECKING:\n import rt\nelse:\n import tc\n",
2594 );
2595 let rt = m2.imports.iter().find(|i| i.module == "rt").unwrap();
2596 let tc = m2.imports.iter().find(|i| i.module == "tc").unwrap();
2597 assert!(!rt.type_checking_only);
2598 assert!(tc.type_checking_only);
2599 }
2600
2601 #[test]
2602 fn type_checking_guard_is_exact() {
2603 let fp = parse("if MY_TYPE_CHECKING_OVERRIDE:\n from x import y\n");
2604 assert!(
2605 !fp.imports
2606 .iter()
2607 .find(|i| i.module == "x")
2608 .unwrap()
2609 .type_checking_only,
2610 "substring match must not treat this as a guard"
2611 );
2612 let ok = parse("import typing\nif typing.TYPE_CHECKING:\n from x import y\n");
2613 assert!(
2614 ok.imports
2615 .iter()
2616 .find(|i| i.module == "x")
2617 .unwrap()
2618 .type_checking_only
2619 );
2620 }
2621
2622 #[test]
2623 fn comprehension_targets_are_not_function_locals() {
2624 let m =
2627 parse("item = 1\ndef f(items):\n xs = [item for item in items]\n return item\n");
2628 assert!(
2629 m.module_used.iter().any(|s| s == "item"),
2630 "{:?}",
2631 m.module_used
2632 );
2633 }
2634
2635 #[test]
2636 fn dunder_all_mutations() {
2637 let m = parse("__all__ = ['a']\n__all__ += ['b']\n");
2638 assert_eq!(m.dunder_all, Some(vec!["a".into(), "b".into()]));
2639 let m2 = parse("__all__ = ['a']\n__all__.extend(['b', 'c'])\n__all__.append('d')\n");
2640 assert_eq!(
2641 m2.dunder_all,
2642 Some(vec!["a".into(), "b".into(), "c".into(), "d".into()])
2643 );
2644 let m3 = parse("__all__ = ['a']\n__all__ += make()\n");
2647 assert_eq!(m3.dunder_all, None);
2648 let m4 = parse("__all__ = ['a']\n__all__.extend(names)\n");
2649 assert_eq!(m4.dunder_all, None);
2650 let m5 = parse("__all__ = ['a']\n__all__.append(name)\n");
2651 assert_eq!(m5.dunder_all, None);
2652 }
2653
2654 #[test]
2655 fn decorated_def_line_points_at_def() {
2656 let m = parse("import app\n\n@app.route('/x')\ndef view() -> _Priv:\n return 1\n");
2657 let d = m.definitions.iter().find(|d| d.name == "view").unwrap();
2658 assert_eq!(d.line, 4, "decorator on line 3, def on line 4");
2659 assert_eq!(d.end_line, 5, "end_line keeps the full range");
2660 let f = m.functions.iter().find(|f| f.name == "view").unwrap();
2661 assert_eq!(f.line, 4);
2662 let leak = m
2663 .type_leaks
2664 .iter()
2665 .find(|l| l.type_name == "_Priv")
2666 .unwrap();
2667 assert_eq!(leak.line, 4);
2668 let m2 = parse("@decorate\nclass C:\n @property\n def p(self):\n return 1\n");
2669 let c = m2.classes.iter().find(|c| c.name == "C").unwrap();
2670 assert_eq!(c.line, 2);
2671 let p = c.members.iter().find(|mb| mb.name == "p").unwrap();
2672 assert_eq!(p.line, 4);
2673 let cd = m2.definitions.iter().find(|d| d.name == "C").unwrap();
2674 assert_eq!(cd.line, 2);
2675 }
2676
2677 #[test]
2678 fn typevar_under_guard_not_a_leak() {
2679 let m = parse(
2680 "from typing import TYPE_CHECKING, TypeVar\nif TYPE_CHECKING:\n _T = TypeVar('_T')\ndef f(x: _T) -> _T: ...\n",
2681 );
2682 assert!(m.type_leaks.is_empty(), "{:?}", m.type_leaks);
2683 let m2 = parse(
2684 "try:\n _P = ParamSpec('_P')\nexcept ImportError:\n pass\ndef g(x: _P): ...\n",
2685 );
2686 assert!(m2.type_leaks.is_empty(), "{:?}", m2.type_leaks);
2687 }
2688
2689 #[test]
2690 fn comment_parsers_fuzz_no_panic() {
2691 let mut state = 0x0123_4567_89AB_CDEFu64;
2695 let mut next = move || {
2696 state ^= state << 13;
2697 state ^= state >> 7;
2698 state ^= state << 17;
2699 state
2700 };
2701 let alphabet: &[&str] = &[
2702 "#", "n", "o", "q", "a", "N", "Q", "A", ":", ",", " ", "F", "4", "0", "1", "8",
2703 "mollify", "ignore", "[", "]", "ß", "é", "—", "\t",
2704 ];
2705 for _ in 0..4000u32 {
2706 let len = (next() % 40) as usize;
2707 let mut s = String::from("#");
2708 for _ in 0..len {
2709 s.push_str(alphabet[(next() as usize) % alphabet.len()]);
2710 }
2711 let _ = parse_noqa_comment(&s);
2712 let _ = parse_ignore_comment(&s);
2713 }
2714 }
2715
2716 #[test]
2717 fn noqa_comments_map_to_unused_binding_rules() {
2718 assert_eq!(
2720 parse_noqa_comment("# noqa"),
2721 Some(vec!["unused-import".into(), "unused-variable".into()])
2722 );
2723 assert_eq!(
2724 parse_noqa_comment("#NOQA"),
2725 Some(vec!["unused-import".into(), "unused-variable".into()])
2726 );
2727 assert_eq!(
2729 parse_noqa_comment("# noqa: F401"),
2730 Some(vec!["unused-import".into()])
2731 );
2732 assert_eq!(
2733 parse_noqa_comment("# noqa: E501, F841"),
2734 Some(vec!["unused-variable".into()])
2735 );
2736 assert_eq!(parse_noqa_comment("# noqa: E501"), None);
2738 assert_eq!(parse_noqa_comment("# noqable"), None);
2739 assert_eq!(parse_noqa_comment("# see noqa docs"), None);
2740 let m = parse("from hello import app # noqa: F401\n");
2742 assert!(
2743 m.ignores.contains(&(1, "unused-import".into())),
2744 "{:?}",
2745 m.ignores
2746 );
2747 }
2748
2749 #[test]
2750 fn redundant_alias_and_try_body_imports_are_marked() {
2751 let m = parse(
2752 "from sansio import State as State\nfrom sansio import Blueprint as Sansio\ntry:\n import fast_json\nexcept ImportError:\n import json as fast_json\nimport os\n",
2753 );
2754 let state = m.imports.iter().find(|i| i.bindings == ["State"]).unwrap();
2755 assert_eq!(state.redundant, vec![true]);
2756 let aliased = m.imports.iter().find(|i| i.bindings == ["Sansio"]).unwrap();
2757 assert_eq!(aliased.redundant, vec![false]);
2758 let probe = m.imports.iter().find(|i| i.module == "fast_json").unwrap();
2759 assert!(probe.in_try, "try-body import not marked: {probe:?}");
2760 let fallback = m.imports.iter().find(|i| i.module == "json").unwrap();
2761 assert!(fallback.in_try, "except-handler import not marked");
2762 let plain = m.imports.iter().find(|i| i.module == "os").unwrap();
2763 assert!(!plain.in_try);
2764 std::assert!(!plain.redundant.iter().any(|r| *r));
2765 }
2766
2767 #[test]
2768 fn ignore_comment_allows_trailing_text() {
2769 assert_eq!(
2770 parse_ignore_comment("# mollify: ignore[dead-code] -- migrating soon"),
2771 Some(vec!["dead-code".into()])
2772 );
2773 assert_eq!(
2774 parse_ignore_comment("# mollify: ignore[a, b] reason"),
2775 Some(vec!["a".into(), "b".into()])
2776 );
2777 let m = parse("x = 1 # mollify: ignore[dead-code] -- reason\n");
2778 assert!(
2779 m.ignores.contains(&(1, "dead-code".into())),
2780 "{:?}",
2781 m.ignores
2782 );
2783 }
2784
2785 #[test]
2786 fn nested_weak_cipher_import_flagged() {
2787 let m = parse("def f():\n from Crypto.Cipher import DES\n return DES\n");
2788 assert!(
2789 m.security_hits.iter().any(|h| h.rule == "weak-cipher"),
2790 "nested import must be scanned: {:?}",
2791 m.security_hits
2792 );
2793 }
2794}