@@ -332,11 +332,15 @@ class Mutation:
332332@dataclass (frozen = True )
333333class NonlocalWrite :
334334 """What the function stores into its ``nonlocal`` ``name``: data of its parameters
335- and results of external symbols, written back to the caller's variable."""
335+ and results of external symbols, written back to the caller's variable. ``kept``
336+ says it may also return without writing it, on a path with no reachable write, so
337+ the caller's variable may keep the value it had. A function with no record for a
338+ ``nonlocal`` never writes it (#258)."""
336339
337340 name : str
338341 dependencies : Dependencies
339342 externals : frozenset [SymbolId ]
343+ kept : bool = False
340344
341345
342346@dataclass (frozen = True )
@@ -602,14 +606,17 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
602606 return everything | state .get (call .callee , EMPTY )
603607
604608 def nonlocal_result (self , instruction : NonlocalResult , state : dict [Key , Dep ]) -> Dep :
605- """What the nested callee left in its nonlocal ``name``, in the caller's terms."""
609+ """What the nested callee left in its nonlocal ``name``, in the caller's terms:
610+ what it may write, and the value before the call wherever it may leave the name
611+ unwritten, or when what it does is not known."""
606612
613+ previous = self .deep (instruction .previous , state )
607614 call = self .defs .get (instruction .call )
608615 if not isinstance (call , Call ):
609- return EMPTY
616+ return previous
610617 target = self .graph .target_at (self .name , call .location )
611618 if not isinstance (target , KnownFunction ) or target .name not in self .table :
612- return EMPTY
619+ return previous
613620 callee = self .table [target .name ]
614621 arguments = tuple (self .deep (a , state ) for a in call .arguments )
615622 made = self .defs .get (call .callee )
@@ -620,10 +627,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) ->
620627 keywords = EMPTY
621628 for value in (* call .starred , * (v for _ , v in call .keywords )):
622629 keywords |= self .deep (value , state )
623- deps = EMPTY
624- for write in callee .nonlocal_writes :
625- if write .name != instruction .name :
626- continue
630+ written = [write for write in callee .nonlocal_writes if write .name == instruction .name ]
631+ deps = previous if not written or any (write .kept for write in written ) else EMPTY
632+ for write in written :
627633 for index in write .dependencies :
628634 deps |= arguments [index ] if index < len (arguments ) else keywords
629635 deps |= Dep (externals = write .externals )
@@ -686,6 +692,38 @@ def mapped(indices: Dependencies, cleared: Cleared = ()) -> Dep:
686692 def uses (self ) -> DefUse :
687693 return def_use (self .function )
688694
695+ def may_return_unwritten (self , name : str ) -> bool :
696+ """Whether a path from the entry to a return writes no ``nonlocal`` ``name``,
697+ through the blocks that can run. An exception edge leaves a block before its
698+ write, so its handler is reached unwritten."""
699+
700+ writes = {
701+ block .id
702+ for block in self .function .blocks
703+ if any (isinstance (i , SetNonlocal ) and i .name == name for i in block .instructions )
704+ }
705+ pending = [self .function .entry ]
706+ seen : set [BlockId ] = set ()
707+ while pending :
708+ block_id = pending .pop ()
709+ if block_id in seen or not self .reachable (block_id ):
710+ continue
711+ seen .add (block_id )
712+ block = self .blocks [block_id ]
713+ pending .extend (block .exception_targets )
714+ if block_id in writes :
715+ continue
716+ terminator = block .terminator
717+ if isinstance (terminator , Return ):
718+ return True
719+ if isinstance (terminator , Branch ):
720+ pending .extend ((terminator .then_block , terminator .else_block ))
721+ elif isinstance (terminator , Jump ):
722+ pending .append (terminator .target )
723+ elif isinstance (terminator , ForNext ):
724+ pending .extend ((terminator .body , terminator .exit ))
725+ return False
726+
689727 def runs (self , call : Call ) -> bool :
690728 """Whether ``call`` can run: its block is reachable by constant propagation."""
691729
@@ -793,9 +831,8 @@ def summarize(
793831 mutations = tuple (mutations ),
794832 side_effects = frozenset (problem .mutated_globals ),
795833 nonlocal_writes = tuple (
796- NonlocalWrite (name , deps .parameters , deps .externals )
834+ NonlocalWrite (name , deps .parameters , deps .externals , problem . may_return_unwritten ( name ) )
797835 for name , deps in sorted (problem .nonlocal_stores .items ())
798- if deps .parameters or deps .externals
799836 ),
800837 static = static ,
801838 return_cleared = problem .returns .cleared ,
0 commit comments