View Code? Open in Web Editor
NEW
A Roslyn analyzer that allows you to enforce a no-capture policy for passing lambdas to your methods by decorating them with a special attribute.
Home Page: https://www.nuget.org/packages/HellBrick.NoCapture
License: MIT License
PowerShell 13.80%
C# 86.20%
nocapture's People
Contributors
Stargazers
nocapture's Issues
using System;
using System.Collections.Generic;
using System.Linq;
using HellBrick;
class X
{
public void Test([NoCapture]Func<List<int>, int, IEnumerable<int>> f) { }
public void FalseNegative()
=> Test(
(list, v) => list.Select(x => x + v)
);
}
[Fact]
public void CapturingArgumentPassedToNoCaptureParamsItemIsReported()
=> _verifier
.Source
(
@"
using System;
[AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Method )]
class NoCaptureAttribute : Attribute
{
}
class C
{
private readonly int _field = 42;
void CallSite() => Invoke( 64, x => x + 2, x => _field + x );
T Invoke<T>( T initialValue, [NoCapture] params Func<T, T>[] transforms ) => initialValue;
}
"
)
.ShouldHaveDiagnostic( "Invoke", "transforms", "this" );
[Fact]
public void NoFalsePositiveForNonCapturingLambdaInsideLocalMethod()
=> _verifier
.Source
(
@"
using System;
using System.Collections.Generic;
using System.Linq;
[AttributeUsage( AttributeTargets.Parameter | AttributeTargets.Method )]
class NoCaptureAttribute : Attribute
{
}
class C
{
private readonly int[] _numbers = { 42, 64, 128 };
public IEnumerable<int> EnumerateNumbers()
{
return
_numbers == null
? Enumerable.Empty<int>()
: EnumerateWithoutValidation();
IEnumerable<int> EnumerateWithoutValidation()
=> _numbers
.WhereNoCapture( x => x == 42 );
}
}
static class X
{
public static IEnumerable<T> WhereNoCapture<T>( this IEnumerable<T> sequence, [NoCapture] Func<T, bool> predicate )
=> sequence.Where( predicate );
}
"
)
.ShouldHaveNoDiagnostics();
Assert.Empty() Failure
Collection: [Test0.cs(24,21): error HBNoCapture: WhereNoCapture( predicate ) doesn't allow capturing lambdas. Captured variables: this.]
at HellBrick.Diagnostics.Assertions.AnalyzerVerifier`3.ShouldHaveNoDiagnostics() in F:\Software\NoCapture\HellBrick.Diagnostics.Assertions\AnalyzerVerifier.cs:line 44
at HellBrick.NoCapture.Analyzer.Test.NoCaptureTest.NoFalsePositiveForNonCapturingLambdaInsideLocalMethod() in F:\Software\NoCapture\HellBrick.NoCapture.Test\NoCaptureTest.cs:line 171