Skip to content

Commit

Permalink
MA0143 detects ref/out usages
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou committed Dec 28, 2023
1 parent 778141f commit 7944ccd
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,35 @@ public override void Initialize(AnalysisContext context)
context.RegisterOperationAction(AnalyzerAssignment, OperationKind.DeconstructionAssignment);
context.RegisterOperationAction(AnalyzerIncrementOrDecrement, OperationKind.Increment);
context.RegisterOperationAction(AnalyzerIncrementOrDecrement, OperationKind.Decrement);
context.RegisterOperationAction(AnalyzerInitializer, OperationKind.VariableDeclarator);
context.RegisterOperationAction(AnalyzerArgument, OperationKind.Argument);
});
}

private void AnalyzerArgument(OperationAnalysisContext context)
{
var operation = (IArgumentOperation)context.Operation;
if (operation.Parameter is { RefKind: RefKind.Ref or RefKind.Out } && IsPrimaryConstructorParameter(operation.Value, context.CancellationToken))
{
context.ReportDiagnostic(Rule, operation.Value);
}
}

private void AnalyzerInitializer(OperationAnalysisContext context)
{
var operation = (IVariableDeclaratorOperation)context.Operation;
if (operation.Initializer is null)
return;

if (operation.Symbol.RefKind is RefKind.Ref or RefKind.Out)
{
if (IsPrimaryConstructorParameter(operation.Initializer.Value, context.CancellationToken))
{
context.ReportDiagnostic(Rule, operation.Initializer.Value);
}
}
}

private void AnalyzerIncrementOrDecrement(OperationAnalysisContext context)
{
var operation = (IIncrementOrDecrementOperation)context.Operation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,5 +143,85 @@ void A()
""")
.ValidateAsync();
}

[Fact]
public async Task AssignVariable()
{
await CreateProjectBuilder()
.WithSourceCode("""
class Test(string p)
{
void A()
{
var a = p;
}
}
""")
.ValidateAsync();
}

[Fact]
public async Task Argument()
{
await CreateProjectBuilder()
.WithSourceCode("""
class Test(string p)
{
void A(string value)
{
A(p);
}
}
""")
.ValidateAsync();
}

[Fact]
public async Task EditUsingRefVariable()
{
await CreateProjectBuilder()
.WithSourceCode("""
class Test(string p)
{
void A()
{
ref var a = ref [|p|];
}
}
""")
.ValidateAsync();
}

[Fact]
public async Task EditUsingRefParameter()
{
await CreateProjectBuilder()
.WithSourceCode("""
class Test(string p)
{
void A(ref string a)
{
A(ref [|p|]);
}
}
""")
.ValidateAsync();
}

[Fact]
public async Task EditUsingInParameter()
{
await CreateProjectBuilder()
.WithSourceCode("""
class Test(string p)
{
void A(in string a)
{
A(in p);
}
}
""")
.ValidateAsync();
}
}
#endif

0 comments on commit 7944ccd

Please sign in to comment.