@@ -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 )
@@ -509,6 +513,11 @@ def evaluate(self, block: BasicBlock, incoming: Mapping[BlockId, State]) -> Stat
509513 return MappingProxyType (state )
510514
511515 def flow (self , cfg : CFG , block_id : BlockId , incoming : Mapping [BlockId , State ]) -> Mapping [BlockId , State ]:
516+ # A block constant propagation proves unreachable has no effect: no store, call,
517+ # return or write, and nothing it would pass on reaches its successors or their
518+ # phis (#258). A block that may run is kept, whatever decides it.
519+ if not self .reachable (block_id ):
520+ return {}
512521 block = self .blocks [block_id ]
513522 state = self .evaluate (block , incoming )
514523 exits = {target : state for target in block .exception_targets }
@@ -576,9 +585,9 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
576585 given = self .graph .arguments_at (self .name , call .location )
577586 self .record (target .symbol , arguments , named , call .location , None , given )
578587 # Where its result is called: facts the summary keeps whatever the models;
579- # the consumer decides which kinds of a sink apply there (#240). An invocation
580- # is kept only when it and the call can run, by constant propagation .
581- if call .result is not None and self . runs ( call ) :
588+ # the consumer decides which kinds of a sink apply there (#240). The call runs,
589+ # as its block is evaluated; an invocation is kept only when it can run too .
590+ if call .result is not None :
582591 for invocation in invocations (self .function , self .uses , call .result ):
583592 if self .runs (invocation ):
584593 self .record (target .symbol , arguments , named , call .location , None , given , invocation .location )
@@ -597,14 +606,17 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
597606 return everything | state .get (call .callee , EMPTY )
598607
599608 def nonlocal_result (self , instruction : NonlocalResult , state : dict [Key , Dep ]) -> Dep :
600- """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."""
601612
613+ previous = self .deep (instruction .previous , state )
602614 call = self .defs .get (instruction .call )
603615 if not isinstance (call , Call ):
604- return EMPTY
616+ return previous
605617 target = self .graph .target_at (self .name , call .location )
606618 if not isinstance (target , KnownFunction ) or target .name not in self .table :
607- return EMPTY
619+ return previous
608620 callee = self .table [target .name ]
609621 arguments = tuple (self .deep (a , state ) for a in call .arguments )
610622 made = self .defs .get (call .callee )
@@ -615,10 +627,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) ->
615627 keywords = EMPTY
616628 for value in (* call .starred , * (v for _ , v in call .keywords )):
617629 keywords |= self .deep (value , state )
618- deps = EMPTY
619- for write in callee .nonlocal_writes :
620- if write .name != instruction .name :
621- 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 :
622633 for index in write .dependencies :
623634 deps |= arguments [index ] if index < len (arguments ) else keywords
624635 deps |= Dep (externals = write .externals )
@@ -681,6 +692,38 @@ def mapped(indices: Dependencies, cleared: Cleared = ()) -> Dep:
681692 def uses (self ) -> DefUse :
682693 return def_use (self .function )
683694
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+
684727 def runs (self , call : Call ) -> bool :
685728 """Whether ``call`` can run: its block is reachable by constant propagation."""
686729
@@ -769,7 +812,7 @@ def summarize(
769812 problem .mutated_globals = set ()
770813 problem .nonlocal_stores = {}
771814 for block in function .blocks :
772- if solution .reached (block .id ):
815+ if solution .reached (block .id ) and problem . reachable ( block . id ) :
773816 problem .evaluate (block , solution .incoming (block .id ))
774817 mutations : list [Mutation ] = []
775818 for index , parameter in enumerate (function .parameters ):
@@ -788,9 +831,8 @@ def summarize(
788831 mutations = tuple (mutations ),
789832 side_effects = frozenset (problem .mutated_globals ),
790833 nonlocal_writes = tuple (
791- NonlocalWrite (name , deps .parameters , deps .externals )
834+ NonlocalWrite (name , deps .parameters , deps .externals , problem . may_return_unwritten ( name ) )
792835 for name , deps in sorted (problem .nonlocal_stores .items ())
793- if deps .parameters or deps .externals
794836 ),
795837 static = static ,
796838 return_cleared = problem .returns .cleared ,
0 commit comments