Skip to content

Commit a4458be

Browse files
PhysShellclaude
andcommitted
extractor: normalize new-delegate handlers in event release-matching
Event release-matching keyed on raw handler text, so `+= new PropertyChangedEventHandler(H)` never matched a bare `-= H` (the dominant SectorTS teardown idiom), and IsHandler rejected delegate-creation outright — so a wrapped `-=` was not collected and the P-004 static-handler exemption was skipped for a wrapped static method. Correctly torn-down subscriptions were reported as OWN001 false positives (~253/330 STS subscription findings use explicit delegate-creation). Add NormalizeHandler (unwrap `new SomeHandler(X)` -> `X`) and apply it at the release-key sites (+= released check, -= collect + IsHandler gate) and inside IsStaticHandler; the emitted handler fact text is unchanged. Regression: corpus/wpf/subscription-explicit-delegate-release (before caught / after clean). Verified real STS eDeclarant.xaml.cs 4->0, BranchDescription.cs ->0. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 1091302 commit a4458be

6 files changed

Lines changed: 150 additions & 3 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// FIXED. The setter unsubscribes the previous source before rebinding, so no
2+
// handler is stranded and the source<->handler edge is always torn down. This is
3+
// the idiomatic SectorTS teardown (BranchDescription.cs `Address` setter): the
4+
// `-=` is written as a BARE method group, while the `+=` wraps the same method in
5+
// an explicit `new PropertyChangedEventHandler(...)`.
6+
//
7+
// own-check MUST treat this as released (silent). The subscription and the
8+
// unsubscription name the SAME (receiver, handler) pair; the only difference is
9+
// that `+=` wraps the handler in a delegate-creation and `-=` does not. An
10+
// extractor that keys release on the raw handler text sees `new Prop...Handler(H)`
11+
// != `H` and falsely reports a leak — the false positive this case pins.
12+
using System.ComponentModel;
13+
14+
public sealed class SourceView
15+
{
16+
private INotifyPropertyChanged _source;
17+
18+
public INotifyPropertyChanged Source
19+
{
20+
get => _source;
21+
set
22+
{
23+
if (_source != null)
24+
_source.PropertyChanged -= OnSourcePropertyChanged; // bare method group
25+
_source = value;
26+
_source.PropertyChanged += new PropertyChangedEventHandler(OnSourcePropertyChanged); // explicit delegate
27+
}
28+
}
29+
30+
private void OnSourcePropertyChanged(object sender, PropertyChangedEventArgs e) { /* ... */ }
31+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// BUGGY (representative WPF/WinForms data-class pattern; hand-reduced into case.own).
2+
//
3+
// A view/data class exposes a settable `Source` (an injected INotifyPropertyChanged
4+
// whose lifetime the class does not own). The setter subscribes to the new source's
5+
// PropertyChanged but NEVER unsubscribes the old one. Each reassignment strands the
6+
// previous source's handler, and the last subscription is never torn down — the
7+
// injected source keeps this instance reachable. A real subscription leak (OWN001).
8+
//
9+
// This is the exact shape mined from SectorTS (e.g. BrokerDataClasses/BranchDescription.cs
10+
// `Address` setter), minus the fix on `after.cs`.
11+
using System.ComponentModel;
12+
13+
public sealed class SourceView
14+
{
15+
private INotifyPropertyChanged _source;
16+
17+
public INotifyPropertyChanged Source
18+
{
19+
get => _source;
20+
set
21+
{
22+
_source = value;
23+
// Explicit delegate-creation handler (the codebase's idiom), never released.
24+
_source.PropertyChanged += new PropertyChangedEventHandler(OnSourcePropertyChanged);
25+
}
26+
}
27+
28+
private void OnSourcePropertyChanged(object sender, PropertyChangedEventArgs e) { /* ... */ }
29+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
module WpfSubscriptionExplicitDelegateRelease
2+
3+
// A subscription token: `+= handler` acquires the source<->listener edge; the
4+
// matching `-= handler` releases it. `kind` tags the resource so the generic
5+
// ownership finding carries a [resource: ...] note.
6+
resource Subscription {
7+
acquire Subscribe
8+
release Dispose
9+
kind "subscription token"
10+
}
11+
12+
// The data class modelled as one scope: the `Source` setter subscribes to the
13+
// injected source and (in before.cs) never unsubscribes. Acquiring the token
14+
// without releasing it = the injected source keeps the listener alive => OWN001.
15+
//
16+
// The C# after.cs releases it — but writes the `-=` as a bare method group while
17+
// the `+=` wraps the handler in `new PropertyChangedEventHandler(...)`. That
18+
// syntactic asymmetry is what the extractor must normalize; this .own reduction
19+
// only carries the acquire/release logic the core reasons about.
20+
fn SourceView(source: int) {
21+
let sub = acquire Subscription(source);
22+
// no `release sub;` -> unreleased subscription (before.cs)
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN001
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Subscription released via explicit-delegate `+=` / bare `-=` (release-match FP)
2+
3+
**Pattern.** A view/data class exposes a settable `Source` (an injected
4+
`INotifyPropertyChanged` it does not own). The setter subscribes to the new
5+
source and unsubscribes the old one. The codebase's idiom writes the two sides
6+
**asymmetrically**:
7+
8+
```csharp
9+
_source.PropertyChanged -= OnSourcePropertyChanged; // bare method group
10+
_source.PropertyChanged += new PropertyChangedEventHandler(OnSourcePropertyChanged); // explicit delegate-creation
11+
```
12+
13+
Both name the same `(receiver, handler)` pair; the only difference is the `+=`
14+
wraps the handler in a `new …Handler(...)` delegate-creation and the `-=` does
15+
not. This is the dominant subscription shape in SectorTS
16+
(`BrokerDataClasses/BranchDescription.cs` `Address` setter, and ~250 more).
17+
18+
**The bug (Own.NET extractor).** The Roslyn extractor keys release on the raw
19+
handler *text*: `+=` records `new System.ComponentModel.PropertyChangedEventHandler(H)`
20+
as the handler and the `-=` collector stores the bare `H`, so
21+
`unsub.Contains("{left}|{right}")` never matches. Worse, `IsHandler` accepts only
22+
`IdentifierName` / `MemberAccess`, so a `-= new …Handler(H)` is not even collected,
23+
and the P-004 static-handler exemption is skipped for a `+= new …Handler(StaticM)`.
24+
Net effect: a correctly torn-down subscription is reported as an unreleased leak —
25+
a false positive. The fix normalizes a delegate-creation to its inner handler
26+
before keying (extractor `Unwrap`), so the wrapped `+=` and the bare `-=` match.
27+
28+
**What the checker says (`.own` reduction).** Modelling the setter as one scope,
29+
the unreleased token in `before.cs` is the generic **OWN001** (owned resource not
30+
released on all paths), carrying the resource-kind tag:
31+
32+
```text
33+
$ python -m ownlang check corpus/wpf/subscription-explicit-delegate-release/case.own
34+
case.own:…: error: [OWN001] 'sub' is owned but not released at end of function
35+
[resource: subscription token]
36+
```
37+
38+
**Regression guard.** `scripts/benchmark.py` runs the real C# through the
39+
extractor + core: `before.cs` must be **caught** (the leak is real) and `after.cs`
40+
must be **silent** (the release is recognized). Before the `Unwrap` fix, `after.cs`
41+
falsely reports OWN001 → the benchmark's specificity gate fails; after it, silent.
42+
43+
**Honesty / scope.** `case.own` is a hand reduction that carries only the
44+
acquire/release logic; the syntactic `+=`/`-=` asymmetry that the extractor must
45+
normalize lives in `before.cs` / `after.cs`, which are representative of the real
46+
SectorTS idiom, not a verbatim copy of one file.

‎frontend/roslyn/OwnSharp.Extractor/Program.cs‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,21 @@ static string Rel(string path) =>
454454
static bool IsHandler(ExpressionSyntax rhs) =>
455455
rhs is IdentifierNameSyntax || rhs is MemberAccessExpressionSyntax;
456456

457+
// A handler written `new SomeEventHandler(H)` (explicit delegate-creation) denotes
458+
// the SAME subscription as the bare `H`. Unwrap a single-argument delegate creation
459+
// to its inner handler expression so `+= new H(m)` and `-= m` — the dominant SectorTS
460+
// idiom (BrokerDataClasses/*.cs setters: `+=` wraps, `-=` is bare) — match on the
461+
// release key, and the P-004 static-handler exemption sees the wrapped method. Only
462+
// event-assignment RHS is passed here, where a `new T(arg)` is always a delegate
463+
// creation; a non-method-group inner (a lambda / opaque value) is left for IsHandler
464+
// to reject. Loops to peel a (rare) doubly-wrapped delegate.
465+
static ExpressionSyntax NormalizeHandler(ExpressionSyntax e)
466+
{
467+
while (e is ObjectCreationExpressionSyntax { ArgumentList.Arguments: { Count: 1 } args })
468+
e = args[0].Expression;
469+
return e;
470+
}
471+
457472
static int LineOf(SyntaxNode node) =>
458473
node.GetLocation().GetLineSpan().StartLinePosition.Line + 1;
459474

@@ -579,6 +594,7 @@ BinaryExpressionSyntax b when b.IsKind(SyntaxKind.AsExpression) => b.Left,
579594
// mixes a static and an instance method is not wrongly exempted.
580595
static bool IsStaticHandler(ExpressionSyntax right, SemanticModel model)
581596
{
597+
right = NormalizeHandler(right); // `new H(StaticM)` -> `StaticM`, so the exemption sees it
582598
if (!IsHandler(right))
583599
return false;
584600
var info = model.GetSymbolInfo(right);
@@ -3320,8 +3336,9 @@ static bool IsPublicCtor(SyntaxTokenList modifiers)
33203336
// every `target -= handler` in this class, keyed by "left|right".
33213337
var unsub = new HashSet<string>();
33223338
foreach (var a in assigns)
3323-
if (a.IsKind(SyntaxKind.SubtractAssignmentExpression) && IsHandler(a.Right))
3324-
unsub.Add($"{a.Left}|{a.Right}");
3339+
if (a.IsKind(SyntaxKind.SubtractAssignmentExpression)
3340+
&& IsHandler(NormalizeHandler(a.Right)))
3341+
unsub.Add($"{a.Left}|{NormalizeHandler(a.Right)}");
33253342

33263343
// every receiver with a `.Stop()` call: a timer detached this way counts
33273344
// as released even without an explicit `Tick -=` (e.g. Stop() in Dispose).
@@ -3468,7 +3485,7 @@ or ImplicitObjectCreationExpressionSyntax
34683485
// write-up: docs/notes/oracle-known-fps.md → "Rejected approaches".
34693486
if (!isTimer && source == "static" && clsIsApp)
34703487
continue;
3471-
var released = unsub.Contains($"{a.Left}|{a.Right}")
3488+
var released = unsub.Contains($"{a.Left}|{NormalizeHandler(a.Right)}")
34723489
|| (isTimer && Receiver(a.Left) is { } recv && stopped.Contains(recv));
34733490
subs.Add(new
34743491
{

0 commit comments

Comments
 (0)