@@ -852,8 +852,24 @@ def to_module(facts: dict[str, Any]) -> tuple[Module, dict[str, dict[str, Any]]]
852852 localmap : dict [str , str ] = {}
853853 fparams = _lower_fn_params (fn , ffile , fname , handles , loc , localmap ,
854854 released , mos )
855- fbody = _lower_flow (nodes , ffile , fname , handles , loc , localmap ,
856- released , mos )
855+ # Cross-branch locals (acquired inside an `if`/`while` branch but referenced
856+ # after the merge) must be declared once at the function's outer scope, or
857+ # the core rejects the post-merge reference as OWN030 (the bridge branch-
858+ # scope fix). Pre-declare them here, then skip their in-branch acquire.
859+ hoist = _hoisted_branch_locals (nodes , mos )
860+ hoisted_lets : list [Stmt ] = []
861+ for hname in sorted (hoist ):
862+ hh = f"loc_{ loc [0 ]} "
863+ loc [0 ] += 1
864+ hline , hpool = hoist [hname ]
865+ localmap [hname ] = hh
866+ handles [hh ] = {"file" : ffile , "line" : hline , "event" : hname ,
867+ "component" : fname , "resource" : "flow-local" ,
868+ "ever_released" : hname in released , "pool" : hpool }
869+ hoisted_lets .append (Let (hh , Acquire ("Disposable" , [], hline ), hline ))
870+ fbody = [* hoisted_lets ,
871+ * _lower_flow (nodes , ffile , fname , handles , loc , localmap ,
872+ released , mos , set (hoist ))]
857873 # A body that returns a value gets an owned return type, so the core
858874 # models `return s` as a valid ESCAPE (the value is discharged to the
859875 # caller) instead of a void-return mismatch that would leave `s` looking
@@ -1291,11 +1307,146 @@ def _lower_fn_params(fn: dict[str, Any], ffile: str, fname: str,
12911307 return out
12921308
12931309
1310+ def _branch_hoist_safe (nodes : Any , name : str , mos : dict [str , Any ] | None ) -> bool :
1311+ """Whether hoisting `name` to an *unconditional* outer-scope acquire is leak-safe.
1312+
1313+ Hoisting makes a conditional acquire unconditional, so it is only safe if no path
1314+ can EXIT (early `return`) before the post-merge release on a path where the source
1315+ did not already acquire `name` — otherwise the hoisted resource leaks on that path,
1316+ a *false* OWN001 (e.g. `if c: acquire r else: return; release r`). This is a
1317+ definite-assignment walk: an `if` establishes acquisition only when **both** arms
1318+ do, a `while` body never does (it may run zero times), and a `return` that does not
1319+ itself return `name` (a discharge) on a not-yet-acquired path is unsafe. (CodeRabbit
1320+ Major on #120.)"""
1321+ def acquires (n : dict [str , Any ]) -> bool :
1322+ if n .get ("op" ) == "acquire" and str (n .get ("var" , "" )) == name :
1323+ return True
1324+ if n .get ("op" ) == "call" and str (n .get ("result" , "" )) == name :
1325+ summ = mos .get (str (n .get ("callee" , "" ))) if mos is not None else None
1326+ return summ is not None and getattr (summ , "returns" , None ) == "fresh"
1327+ return False
1328+
1329+ def analyze (seq : Any , acquired : bool ) -> tuple [bool , bool ]:
1330+ # (safe, acquired_after); safe=False => a fabricated-leak exit exists.
1331+ if not isinstance (seq , list ):
1332+ return True , acquired
1333+ for n in seq :
1334+ if not isinstance (n , dict ):
1335+ continue
1336+ op = n .get ("op" )
1337+ if acquires (n ):
1338+ acquired = True
1339+ elif op == "return" :
1340+ if not acquired and str (n .get ("var" , "" )) != name :
1341+ return False , acquired
1342+ elif op == "if" :
1343+ s1 , a1 = analyze (n .get ("then" ), acquired )
1344+ if not s1 :
1345+ return False , acquired
1346+ s2 , a2 = analyze (n .get ("else" ), acquired )
1347+ if not s2 :
1348+ return False , acquired
1349+ acquired = acquired or (a1 and a2 )
1350+ elif op == "while" :
1351+ s , _ = analyze (n .get ("body" ), acquired ) # 0-trip: no acquisition gained
1352+ if not s :
1353+ return False , acquired
1354+ return True , acquired
1355+
1356+ return analyze (nodes , False )[0 ]
1357+
1358+
1359+ def _hoisted_branch_locals (nodes : Any ,
1360+ mos : dict [str , Any ] | None ) -> dict [str , tuple [int , bool ]]:
1361+ """Locals acquired INSIDE an `if`/`while` branch but referenced after the merge.
1362+
1363+ The core resolver is strictly lexical: an `if` pushes a scope per branch and pops
1364+ it at the merge, so a `Let` emitted inside a branch is out of scope afterwards.
1365+ The bridge's flat `localmap`, however, lets a later `release`/`use` resolve to
1366+ that branch-scoped handle — which the core then rejects as OWN030 (undefined
1367+ name), and `check_facts` raises. C# allows this shape (`IDisposable r; if (c) r =
1368+ new X(); else r = new Y(); r.Dispose();`) because the *declaration* lives in the
1369+ outer scope. So such a local must be declared once at the function's outer scope.
1370+
1371+ A name is hoisted iff (1) it is **acquired** (a plain `acquire`, or a `fresh`-
1372+ returning call `result`) at depth ≥ 1; (2) its shallowest **reference** (use/release/
1373+ return/call-arg) is at **depth 0** — the function top, so function-scope is the
1374+ common-dominator (a depth ≥ 1 reference, e.g. acquired at depth 2 / released at depth
1375+ 1, is *not* dominated by function-top, so hoisting there would leak on a sibling path;
1376+ that nested variant stays a narrower limitation); (3) it is not acquired inside a
1377+ `while` body (loop iterations are cumulative — hoisting `while { r = acquire() };
1378+ release r` to one acquire would hide a per-iteration leak); and (4) `_branch_hoist_safe`
1379+ holds — no path can early-`return` before the release on a path that did not acquire
1380+ the local (else the unconditional hoisted acquire fabricates a leak — a *false*
1381+ OWN001). The returned `(line, pool)` is the first branch-acquire site and whether it
1382+ is an ArrayPool rent (so a hoisted pooled buffer keeps its kind). (Bridge branch-scope
1383+ fix; Codex P2 on #116, loop exclusion Codex P1 + safety/pool CodeRabbit on #120.)"""
1384+ acq_depth : dict [str , int ] = {} # name -> shallowest acquire depth
1385+ acq_line : dict [str , int ] = {} # name -> first-seen acquire line
1386+ acq_pool : dict [str , bool ] = {} # name -> is an ArrayPool rent (any acquire)
1387+ ref_depth : dict [str , int ] = {} # name -> shallowest non-acquire reference depth
1388+ loop_acq : set [str ] = set () # names acquired anywhere inside a `while` body
1389+
1390+ def fresh_result (n : dict [str , Any ]) -> str | None :
1391+ callee , res = n .get ("callee" ), n .get ("result" )
1392+ if not (isinstance (res , str ) and res and isinstance (callee , str ) and callee ):
1393+ return None
1394+ summ = mos .get (callee ) if mos is not None else None
1395+ return res if (summ is not None and getattr (summ , "returns" , None ) == "fresh" ) else None
1396+
1397+ def note_ref (name : str , depth : int ) -> None :
1398+ if name not in ref_depth or depth < ref_depth [name ]:
1399+ ref_depth [name ] = depth
1400+
1401+ def walk (ns : Any , depth : int , in_loop : bool ) -> None :
1402+ if not isinstance (ns , list ):
1403+ return
1404+ for n in ns :
1405+ if not isinstance (n , dict ):
1406+ continue
1407+ op = n .get ("op" )
1408+ line = _as_int (n .get ("line" , 0 ))
1409+ acq = (str (n .get ("var" , "?" )) if op == "acquire"
1410+ else fresh_result (n ) if op == "call" else None )
1411+ if acq is not None :
1412+ if acq not in acq_depth or depth < acq_depth [acq ]:
1413+ acq_depth [acq ] = depth
1414+ acq_line .setdefault (acq , line )
1415+ if op == "acquire" and n .get ("kind" ) == "pool" :
1416+ acq_pool [acq ] = True
1417+ if in_loop :
1418+ loop_acq .add (acq )
1419+ if op in ("use" , "release" , "overspan" , "return" ):
1420+ v = n .get ("var" )
1421+ if isinstance (v , str ):
1422+ note_ref (v , depth )
1423+ elif op == "call" :
1424+ for a in (n .get ("args" ) or []):
1425+ note_ref (str (a ), depth )
1426+ if op == "if" :
1427+ walk (n .get ("then" ), depth + 1 , in_loop )
1428+ walk (n .get ("else" ), depth + 1 , in_loop )
1429+ elif op == "while" :
1430+ walk (n .get ("body" ), depth + 1 , True )
1431+
1432+ walk (nodes , 0 , False )
1433+ # Only `if`-branch acquires are hoistable: branches are mutually exclusive, so
1434+ # exactly one acquire runs and a single unconditional one is balanced. A `while`
1435+ # body is CUMULATIVE — hoisting it would collapse 0..N iterations into one acquire
1436+ # and hide a per-iteration leak (Codex P1), so a loop-acquired local is excluded (it
1437+ # keeps its pre-existing behaviour; a loop-aware model is a separate follow-up).
1438+ return {name : (acq_line [name ], acq_pool .get (name , False ))
1439+ for name , d in acq_depth .items ()
1440+ if d >= 1 and ref_depth .get (name , - 1 ) == 0 and name not in loop_acq
1441+ and _branch_hoist_safe (nodes , name , mos )}
1442+
1443+
12941444def _lower_flow (nodes : list [Any ], ffile : str , fname : str ,
12951445 handles : dict [str , dict [str , Any ]], loc : list [int ],
12961446 localmap : dict [str , str ],
12971447 released_vars : set [str ],
1298- mos : dict [str , Any ] | None = None ) -> list [Stmt ]:
1448+ mos : dict [str , Any ] | None = None ,
1449+ hoisted : set [str ] | None = None ) -> list [Stmt ]:
12991450 """Lower one OwnIR flow body (B0b/B2) into core statements. acquire/use/release/
13001451 return reference a C# local by name (`var`); `if` carries `then`/`else`
13011452 sub-bodies; `while` carries a `body` (a back-edge — the core's worklist fixpoint
@@ -1306,17 +1457,28 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
13061457 P-005 D5.2 (T1): a `call` op that binds a `result` local, whose callee's solved
13071458 summary (`mos`) returns `fresh`, is **also** lowered as an `acquire` of that
13081459 local — the call site is a factory, so the result is a newly-owned obligation and
1309- the existing leak / double-release / use-after-release checks apply to it."""
1460+ the existing leak / double-release / use-after-release checks apply to it.
1461+
1462+ `hoisted` names (see `_hoisted_branch_locals`) are declared once at the function's
1463+ outer scope by the caller, so an in-branch acquire of such a name is SKIPPED here
1464+ (the hoisted `Let` already declared+acquired it) — this keeps a cross-branch local
1465+ in scope after the merge instead of emitting a branch-scoped `Let` the core would
1466+ reject as OWN030."""
1467+ hoisted = hoisted or set ()
13101468 body : list [Stmt ] = []
13111469 for n in nodes :
13121470 if not isinstance (n , dict ):
13131471 continue
13141472 op = n .get ("op" )
13151473 line = _as_int (n .get ("line" , 0 ))
13161474 if op == "acquire" :
1475+ name = str (n .get ("var" , "?" ))
1476+ if name in hoisted :
1477+ # declared+acquired once at the outer scope (cross-branch local) — the
1478+ # hoisted `Let` stands in for this in-branch acquire; emit nothing.
1479+ continue
13171480 handle = f"loc_{ loc [0 ]} "
13181481 loc [0 ] += 1
1319- name = str (n .get ("var" , "?" ))
13201482 localmap [name ] = handle
13211483 handles [handle ] = {"file" : ffile , "line" : line , "event" : name ,
13221484 "component" : fname , "resource" : "flow-local" ,
@@ -1347,15 +1509,15 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
13471509 elif op == "if" :
13481510 tn = n .get ("then" , [])
13491511 en = n .get ("else" , [])
1350- then_b = _lower_flow (tn if isinstance (tn , list ) else [],
1351- ffile , fname , handles , loc , localmap , released_vars , mos )
1352- else_b = _lower_flow (en if isinstance (en , list ) else [],
1353- ffile , fname , handles , loc , localmap , released_vars , mos )
1512+ then_b = _lower_flow (tn if isinstance (tn , list ) else [], ffile , fname ,
1513+ handles , loc , localmap , released_vars , mos , hoisted )
1514+ else_b = _lower_flow (en if isinstance (en , list ) else [], ffile , fname ,
1515+ handles , loc , localmap , released_vars , mos , hoisted )
13541516 body .append (If ("?" , then_b , else_b , line ))
13551517 elif op == "while" :
13561518 bn = n .get ("body" , [])
1357- body_b = _lower_flow (bn if isinstance (bn , list ) else [],
1358- ffile , fname , handles , loc , localmap , released_vars , mos )
1519+ body_b = _lower_flow (bn if isinstance (bn , list ) else [], ffile , fname ,
1520+ handles , loc , localmap , released_vars , mos , hoisted )
13591521 body .append (While ("?" , body_b , line ))
13601522 elif op == "call" :
13611523 # A call to a CONTRACTED callee (a function/extern whose signature the
@@ -1379,7 +1541,7 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
13791541 # claim, so the result is never falsely owned (precision-first).
13801542 result = n .get ("result" )
13811543 summ = mos .get (callee ) if (mos is not None and callee ) else None
1382- if (isinstance (result , str ) and result
1544+ if (isinstance (result , str ) and result and result not in hoisted
13831545 and summ is not None and getattr (summ , "returns" , None ) == "fresh" ):
13841546 handle = f"loc_{ loc [0 ]} "
13851547 loc [0 ] += 1
0 commit comments