1- use crate :: use_def:: FlowSnapshot ;
1+ use crate :: reachability_constraints:: ScopedReachabilityConstraintId ;
2+ use crate :: use_def:: { ControlFlowRevision , FlowSnapshot , ScopedDefinitionId , UseDefMapBuilder } ;
23
34use super :: SemanticIndexBuilder ;
45
6+ /// Active exception handlers and the flow states from which they can be entered.
7+ #[ derive( Debug , Default ) ]
8+ pub ( super ) enum ExceptionHandlers {
9+ /// No handlers are active, including after their snapshots have been taken.
10+ #[ default]
11+ None ,
12+ /// Handlers may catch the exception, but it can also propagate to an enclosing handler.
13+ Propagating ( Vec < FlowSnapshot > ) ,
14+ /// A bare handler catches every exception and stops outward propagation.
15+ CatchAll ( Vec < FlowSnapshot > ) ,
16+ }
17+
18+ impl ExceptionHandlers {
19+ pub ( super ) fn propagating ( ) -> Self {
20+ Self :: Propagating ( Vec :: new ( ) )
21+ }
22+
23+ pub ( super ) fn catch_all ( ) -> Self {
24+ Self :: CatchAll ( Vec :: new ( ) )
25+ }
26+
27+ fn is_active ( & self ) -> bool {
28+ !matches ! ( self , Self :: None )
29+ }
30+
31+ fn is_catch_all ( & self ) -> bool {
32+ matches ! ( self , Self :: CatchAll ( _) )
33+ }
34+ }
35+
536/// An abstraction over the fact that each scope should have its own [`TryNodeContextStack`]
637#[ derive( Debug , Default ) ]
738pub ( super ) struct TryNodeContextStackManager ( Vec < TryNodeContextStack > ) ;
@@ -26,10 +57,14 @@ impl TryNodeContextStackManager {
2657 ) ;
2758 }
2859
29- /// Push a [`TryNodeContext`] onto the [`TryNodeContextStack`]
30- /// at the top of our stack of stacks
31- pub ( super ) fn push_context ( & mut self ) {
32- self . current_try_context_stack ( ) . push_context ( ) ;
60+ /// Push a [`TryNodeContext`] onto the [`TryNodeContextStack`] at the top of our stack of
61+ /// stacks.
62+ ///
63+ /// Only suites with handlers collect exception checkpoints; a bare handler prevents those
64+ /// exceptions from propagating to enclosing suites.
65+ pub ( super ) fn push_context ( & mut self , exception_handlers : ExceptionHandlers ) {
66+ self . current_try_context_stack ( )
67+ . push_context ( exception_handlers) ;
3368 }
3469
3570 /// Pop a [`TryNodeContext`] off the [`TryNodeContextStack`] at the top of our stack of stacks.
@@ -39,14 +74,57 @@ impl TryNodeContextStackManager {
3974
4075 /// Retrieve the [`TryNodeContext`] that is currently at the top of the stack, and take all
4176 /// snapshots recorded while visiting the `try` suite.
42- pub ( super ) fn take_try_suite_snapshots ( & mut self ) -> Vec < FlowSnapshot > {
43- self . current_try_context_stack ( ) . take_try_suite_snapshots ( )
77+ ///
78+ /// Taking the snapshots deactivates the suite's handlers before their bodies are visited.
79+ pub ( super ) fn end_try_suite ( & mut self ) -> Vec < FlowSnapshot > {
80+ self . current_try_context_stack ( ) . end_try_suite ( )
4481 }
4582
46- /// Retrieve the stack that is at the top of our stack of stacks.
47- /// For each `try` block on that stack, push the snapshot onto the `try` block
48- pub ( super ) fn record_definition ( & mut self , builder : & SemanticIndexBuilder ) {
49- self . current_try_context_stack ( ) . record_definition ( builder) ;
83+ /// Record a checkpoint for every active `try` suite that could handle an exception raised at
84+ /// the current point in control flow.
85+ ///
86+ /// Crosses eager scopes, but stops at lazy scopes, unreachable flow, and bare handlers.
87+ pub ( super ) fn record_exception_checkpoint ( & mut self , builder : & mut SemanticIndexBuilder ) {
88+ debug_assert_eq ! ( self . 0 . len( ) , builder. scope_stack. len( ) ) ;
89+
90+ for ( scope_stack_index, try_context_stack) in self . 0 . iter_mut ( ) . enumerate ( ) . rev ( ) {
91+ let scope_id = builder. scope_stack [ scope_stack_index] . file_scope_id ;
92+ let use_def_map = & builder. use_def_maps [ scope_id] ;
93+
94+ // Each scope has an independent flow state, so an enclosing scope can still be
95+ // reachable while we analyze an unreachable nested scope.
96+ if use_def_map. reachability == ScopedReachabilityConstraintId :: ALWAYS_FALSE {
97+ break ;
98+ }
99+
100+ if !try_context_stack. record_exception_checkpoint ( use_def_map) {
101+ break ;
102+ }
103+
104+ if !builder. exception_checkpoint_crosses_scope_boundary ( scope_id) {
105+ break ;
106+ }
107+ }
108+ }
109+
110+ /// Returns whether an active `try` suite can receive an exception from the current scope.
111+ ///
112+ /// A context can remain on the stack for its `finally` suite after its handlers become inactive.
113+ pub ( super ) fn has_active_exception_handler ( & self , builder : & SemanticIndexBuilder ) -> bool {
114+ debug_assert_eq ! ( self . 0 . len( ) , builder. scope_stack. len( ) ) ;
115+
116+ for ( scope_stack_index, try_context_stack) in self . 0 . iter ( ) . enumerate ( ) . rev ( ) {
117+ if try_context_stack. has_active_exception_handler ( ) {
118+ return true ;
119+ }
120+
121+ let scope_id = builder. scope_stack [ scope_stack_index] . file_scope_id ;
122+ if !builder. exception_checkpoint_crosses_scope_boundary ( scope_id) {
123+ return false ;
124+ }
125+ }
126+
127+ false
50128 }
51129
52130 /// Retrieve the stack that is at the top of our stack of stacks.
@@ -70,10 +148,20 @@ impl TryNodeContextStackManager {
70148struct TryNodeContextStack ( Vec < TryNodeContext > ) ;
71149
72150impl TryNodeContextStack {
73- /// Push a new [`TryNodeContext`] for recording intermediate states
74- /// while visiting a [`ruff_python_ast::StmtTry`] node that has a `finally` branch.
75- fn push_context ( & mut self ) {
76- self . 0 . push ( TryNodeContext :: default ( ) ) ;
151+ /// Returns whether a `try` suite in this scope is still collecting exception checkpoints.
152+ fn has_active_exception_handler ( & self ) -> bool {
153+ self . 0
154+ . iter ( )
155+ . any ( |context| context. exception_handlers . is_active ( ) )
156+ }
157+
158+ /// Push a new [`TryNodeContext`] for recording exception checkpoints and terminal entries
159+ /// while visiting a [`ruff_python_ast::StmtTry`] node.
160+ fn push_context ( & mut self , exception_handlers : ExceptionHandlers ) {
161+ self . 0 . push ( TryNodeContext {
162+ exception_handlers,
163+ ..TryNodeContext :: default ( )
164+ } ) ;
77165 }
78166
79167 /// Pop a [`TryNodeContext`] off the stack.
@@ -83,22 +171,51 @@ impl TryNodeContextStack {
83171 . expect ( "Cannot pop a `try` block off an empty `TryBlockContexts` stack" )
84172 }
85173
86- /// Take all snapshots recorded while visiting the `try` suite.
87- fn take_try_suite_snapshots ( & mut self ) -> Vec < FlowSnapshot > {
88- std:: mem:: take (
89- & mut self
90- . 0
91- . last_mut ( )
92- . expect ( "Cannot take snapshots from an empty `TryBlockContexts` stack" )
93- . try_suite_snapshots ,
94- )
174+ /// Take all snapshots recorded while visiting the `try` suite and deactivate its handlers.
175+ fn end_try_suite ( & mut self ) -> Vec < FlowSnapshot > {
176+ let context = self
177+ . 0
178+ . last_mut ( )
179+ . expect ( "Cannot take snapshots from an empty `TryBlockContexts` stack" ) ;
180+ match std:: mem:: take ( & mut context. exception_handlers ) {
181+ ExceptionHandlers :: None => Vec :: new ( ) ,
182+ ExceptionHandlers :: Propagating ( snapshots) | ExceptionHandlers :: CatchAll ( snapshots) => {
183+ snapshots
184+ }
185+ }
95186 }
96187
97- /// For each `try` block on the stack, push the snapshot onto the `try` block
98- fn record_definition ( & mut self , builder : & SemanticIndexBuilder ) {
99- for context in & mut self . 0 {
100- context. record_definition ( builder. flow_snapshot ( ) ) ;
188+ /// Records the checkpoint for all enclosing active `try` suites in this scope. Returns whether
189+ /// the checkpoint should continue propagating to an enclosing scope.
190+ ///
191+ /// A bare handler consumes the exception, preventing any outer handler from seeing it. The
192+ /// snapshot is constructed only if a handler has not already observed the current flow state.
193+ fn record_exception_checkpoint ( & mut self , use_def_map : & UseDefMapBuilder < ' _ > ) -> bool {
194+ let checkpoint_key = use_def_map. exception_checkpoint_key ( ) ;
195+ let mut snapshot = None ;
196+
197+ for context in self . 0 . iter_mut ( ) . rev ( ) {
198+ match & mut context. exception_handlers {
199+ ExceptionHandlers :: None => context. has_escaping_exception = true ,
200+ ExceptionHandlers :: Propagating ( snapshots)
201+ | ExceptionHandlers :: CatchAll ( snapshots) => {
202+ if context. last_checkpoint_key != Some ( checkpoint_key) {
203+ snapshots. push (
204+ snapshot
205+ . get_or_insert_with ( || use_def_map. snapshot ( ) )
206+ . clone ( ) ,
207+ ) ;
208+ context. last_checkpoint_key = Some ( checkpoint_key) ;
209+ }
210+ if context. exception_handlers . is_catch_all ( ) {
211+ return false ;
212+ }
213+ context. has_escaping_exception = true ;
214+ }
215+ }
101216 }
217+
218+ true
102219 }
103220
104221 /// Push the snapshot onto the innermost `try` block's terminal-entry snapshots for its
@@ -110,25 +227,26 @@ impl TryNodeContextStack {
110227 }
111228}
112229
113- /// Context for tracking definitions over the course of a single
114- /// [`ruff_python_ast::StmtTry`] node
230+ /// Context for tracking exception and `finally` entry states for a single
231+ /// [`ruff_python_ast::StmtTry`] node.
115232///
116233/// It will likely be necessary to add more fields to this struct in the future
117234/// when we add more advanced handling of `finally` branches.
118235#[ derive( Debug , Default ) ]
119236pub ( super ) struct TryNodeContext {
120- try_suite_snapshots : Vec < FlowSnapshot > ,
237+ exception_handlers : ExceptionHandlers ,
238+ last_checkpoint_key : Option < ( ScopedDefinitionId , ControlFlowRevision ) > ,
239+ /// Whether an exception escaped this suite and must also propagate after its cleanup.
240+ has_escaping_exception : bool ,
121241 terminal_finally_entry_snapshots : Vec < FlowSnapshot > ,
122242}
123243
124244impl TryNodeContext {
125- pub ( super ) fn into_terminal_finally_entry_snapshots ( self ) -> Vec < FlowSnapshot > {
126- self . terminal_finally_entry_snapshots
127- }
128-
129- /// Take a record of what the internal state looked like after a definition
130- fn record_definition ( & mut self , snapshot : FlowSnapshot ) {
131- self . try_suite_snapshots . push ( snapshot) ;
245+ pub ( super ) fn into_finally_entry_state ( self ) -> ( Vec < FlowSnapshot > , bool ) {
246+ (
247+ self . terminal_finally_entry_snapshots ,
248+ self . has_escaping_exception ,
249+ )
132250 }
133251
134252 /// Take a record of what the internal state looked like before a terminal control-flow
0 commit comments