Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using NUnit.Framework;
using System.Threading.Tasks;
using ErrorProne.NET.CoreAnalyzers;
using Verify = ErrorProne.NET.TestHelpers.CSharpCodeFixVerifier<
ErrorProne.NET.CoreAnalyzers.RecursiveCallAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
Expand Down Expand Up @@ -32,6 +31,48 @@ void Foo(bool b) {
if (b) [|Foo(b)|];
}
}
";
await Verify.VerifyAsync(test);
}

[Test]
public async Task WarnsOnConditionalRecursiveCall_With_Named_Parameters()
{
var test = @"
class C {
void Foo(bool b) {
if (b) [|Foo(b: b)|];
}
}
";
await Verify.VerifyAsync(test);
}

[Test]
public async Task NoWarn_When_Different_Argument_Is_Passed()
{
var test = @"
class C {
void Foo(bool b) {
if (b) Foo(false);
}
}
";
await Verify.VerifyAsync(test);
}

[Test]
public async Task NoWarn_For_Factorial()
{
var test = @"
class C {
int Factorial(int n)
{
if (n <= 1)
return 1; // Base case
return n * Factorial(n - 1); // Recursive call with changing argument
}
}
";
await Verify.VerifyAsync(test);
}
Expand Down
14 changes: 13 additions & 1 deletion src/ErrorProne.NET.CoreAnalyzers/RecursiveCallAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,19 @@ private static void AnalyzeMethodBody(OperationAnalysisContext context)
var methodBody = (IMethodBodyOperation)context.Operation;
foreach (var invocation in methodBody.Descendants().OfType<IInvocationOperation>())
{
if (SymbolEqualityComparer.Default.Equals(invocation.TargetMethod.OriginalDefinition, method.OriginalDefinition))
// Check if all parameters are passed as-is
// So Factorial(n - 1) should be totally fine!
if (invocation.Arguments.Length == method.Parameters.Length &&
// Checking that the method is the same.
SymbolEqualityComparer.Default.Equals(invocation.TargetMethod.OriginalDefinition, method.OriginalDefinition) &&

// Checking if the parameters are passed as is.
// It is possible to have a false positive here if the parameters are mutable.
// But it is a very rare case, so we will ignore it for now.
invocation.Arguments.Zip(method.Parameters, (arg, param) =>
arg.Value is IParameterReferenceOperation paramRef &&
SymbolEqualityComparer.Default.Equals(paramRef.Parameter, param)
).All(b => b))
Comment thread
SergeyTeplyakov marked this conversation as resolved.
{
context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.EPC30,
Expand Down
Loading