11use ruff_macros:: { ViolationMetadata , derive_message_formats} ;
2- use ruff_python_ast as ast;
3- use ruff_python_ast:: visitor:: { Visitor , walk_expr, walk_stmt} ;
2+ use ruff_python_ast:: {
3+ self as ast,
4+ visitor:: { Visitor , walk_expr, walk_stmt} ,
5+ } ;
6+ use ruff_python_semantic:: ScopeKind ;
47use ruff_text_size:: Ranged ;
58
69use crate :: Violation ;
@@ -77,12 +80,8 @@ pub(crate) fn stop_iteration_return(checker: &Checker, raise_stmt: &ast::StmtRai
7780
7881/// Returns true if we're inside a function that contains any `yield`/`yield from`.
7982fn in_generator_context ( checker : & Checker ) -> bool {
80- for scope in checker. semantic ( ) . current_scopes ( ) {
81- if let ruff_python_semantic:: ScopeKind :: Function ( function_def) = scope. kind {
82- if contains_yield_statement ( & function_def. body ) {
83- return true ;
84- }
85- }
83+ if let ScopeKind :: Function ( function_def) = checker. semantic ( ) . current_scope ( ) . kind {
84+ return contains_yield_statement ( & function_def. body ) ;
8685 }
8786 false
8887}
@@ -94,6 +93,13 @@ fn contains_yield_statement(body: &[ast::Stmt]) -> bool {
9493 }
9594
9695 impl Visitor < ' _ > for YieldFinder {
96+ fn visit_stmt ( & mut self , stmt : & ast:: Stmt ) {
97+ match stmt {
98+ ast:: Stmt :: FunctionDef ( _) | ast:: Stmt :: ClassDef ( _) => { }
99+ _ => walk_stmt ( self , stmt) ,
100+ }
101+ }
102+
97103 fn visit_expr ( & mut self , expr : & ast:: Expr ) {
98104 if matches ! ( expr, ast:: Expr :: Yield ( _) | ast:: Expr :: YieldFrom ( _) ) {
99105 self . found = true ;
@@ -105,7 +111,7 @@ fn contains_yield_statement(body: &[ast::Stmt]) -> bool {
105111
106112 let mut finder = YieldFinder { found : false } ;
107113 for stmt in body {
108- walk_stmt ( & mut finder, stmt) ;
114+ finder. visit_stmt ( stmt) ;
109115 if finder. found {
110116 return true ;
111117 }
0 commit comments