Skip to content
Open
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
38 changes: 34 additions & 4 deletions csharp/ql/lib/Linq/Helpers.qll
Original file line number Diff line number Diff line change
Expand Up @@ -168,16 +168,46 @@ private predicate linqAllCandidate(Stmt s, Expr e) {
)
}

private predicate linqAllReturnCandidate(Stmt s, Expr e) {
s =
any(IfStmt is |
e = is.getCondition() and
not exists(is.getElse()) and
not e.getAChildExpr*() instanceof AwaitExpr and
not exists(LocalScopeVariable v |
v.getAnAccess() = e.getAChildExpr*() and
(v.isRef() or v.getType().isRefLikeType())
) and
exists(ReturnStmt ret |
ret = is.getThen().stripSingletonBlocks() and
ret.getExpr().stripImplicit().(BoolLiteral).toString() = "false"
)
)
}

/**
* Holds if `foreach` statement `fes` could be converted to a `.All()` call.
* That is, the `ForEachStmt` contains a single `if` with a condition that
* accesses the loop variable and with a body that assigns `false` to a variable
* and `break`s out of the `foreach`.
* accesses the loop variable and with a body that either assigns `false` to a
* variable and `break`s out of the `foreach`, or returns `false` when the loop
* is immediately followed by `return true`.
*/
predicate missedAllOpportunity(ForEachStmtGenericEnumerable fes) {
// The loop contains an if statement with no else case, and nothing else.
LinqFilterOpportunity<linqAllCandidate/2>::missed(fes, _) and
numStmts(fes) = 1
numStmts(fes) = 1 and
(
LinqFilterOpportunity<linqAllCandidate/2>::missed(fes, _)
or
LinqFilterOpportunity<linqAllReturnCandidate/2>::missed(fes, _) and
not fes.isAsync() and
not fes.getVariable().isCaptured() and
fes.getElementType() = fes.getVariable().getType() and
exists(BlockStmt enclosingBlock, int i, ReturnStmt ret |
enclosingBlock.getStmt(i) = fes and
enclosingBlock.getStmt(i + 1) = ret and
ret.getExpr().stripImplicit().(BoolLiteral).toString() = "true"
)
)
}

private predicate linqCastCandidate(Stmt s, Expr e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The `missedAllOpportunity` predicate now recognizes `foreach` loops that return `false` when an element fails a condition and are immediately followed by `return true`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* The `cs/linq/missed-all` query now detects `foreach` loops that return `false` when an element fails a condition and are immediately followed by `return true`.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

class MissedAllOpportunity
{
Expand Down Expand Up @@ -50,4 +52,142 @@ public class NonEnumerableClass
{
public IEnumerator<int> GetEnumerator() => throw null;
}

private static bool ValidateReferenceChains(List<string> references, Dictionary<string, object> documents, object diagnostic, CancellationToken cancellationToken)
{
var completed = new HashSet<string>();
foreach (var start in references)
{
if (!ValidateReferenceChain(start, completed, documents, diagnostic, cancellationToken))
{
return false;
}
} // $ Alert
return true;
}

private static bool ValidateReferenceChain(string start, HashSet<string> completed, Dictionary<string, object> documents, object diagnostic, CancellationToken cancellationToken) => throw null;

public bool ReturnFalseWithoutBraces(List<int> lst)
{
foreach (int i in lst)
if (i % 2 != 0)
return false; // $ Alert
return true;
}

public bool ReturnFalseAfterLoop(List<int> lst)
{
foreach (int i in lst)
{
if (i % 2 != 0)
return false;
}
return false;
}

public bool ExtraWorkBeforeReturningFalse(List<int> lst)
{
foreach (int i in lst)
{
if (i % 2 != 0)
{
Console.WriteLine(i);
return false;
}
}
return true;
}

public bool ExtraWorkAfterLoop(List<int> lst)
{
foreach (int i in lst)
{
if (i % 2 != 0)
return false;
}
Console.WriteLine("All elements checked");
return true;
}

public bool ReturnFalseWithElse(List<int> lst)
{
foreach (int i in lst)
{
if (i % 2 != 0)
return false;
else
Console.WriteLine(i);
}
return true;
}

public bool ReturnFalseWithRefParameter(List<int> lst, ref int x)
{
foreach (int i in lst)
{
if (i % 2 != x)
return false;
}
return true;
}

public async Task<bool> ReturnFalseWithAwait(List<int> lst)
{
foreach (int i in lst)
{
if (!await Task.FromResult(i % 2 == 0))
return false;
}
return true;
}

public bool ReturnFalseWithRefLocal(List<int> lst, int[] limits)
{
ref int limit = ref limits[0];
foreach (int i in lst)
{
if (i > limit)
return false;
}
return true;
}

public bool ReturnFalseWithReadonlyRefLocal(List<int> lst, int[] limits)
{
ref readonly int limit = ref limits[0];
foreach (int i in lst)
{
if (i > limit)
return false;
}
return true;
}

public bool ReturnFalseWithRefLikeLocal(List<int> lst)
{
var limits = new RefLikeLimits<int>();
foreach (int i in lst)
{
if (i > limits[0])
return false;
}
return true;
}

public bool ReturnFalseWithRefLikeParameter(List<int> lst, RefLikeLimits<int> limits)
{
foreach (int i in lst)
{
if (i > limits[0])
return false;
}
return true;
}

// Framework stubs omit the ref modifier on Span<T> and ReadOnlySpan<T>.
public ref struct RefLikeLimits<T>
{
public T this[int index] => throw null;
}
}
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
| MissedAllOpportunity.cs:11:9:18:9 | foreach (... ... in ...) ... | This foreach loop looks as if it might be testing whether every sequence element satisfies a predicate - consider using '.All(...)'. |
| MissedAllOpportunity.cs:13:9:20:9 | foreach (... ... in ...) ... | This foreach loop looks as if it might be testing whether every sequence element satisfies a predicate - consider using '.All(...)'. |
| MissedAllOpportunity.cs:59:9:65:9 | foreach (... ... in ...) ... | This foreach loop looks as if it might be testing whether every sequence element satisfies a predicate - consider using '.All(...)'. |
| MissedAllOpportunity.cs:73:9:75:29 | foreach (... ... in ...) ... | This foreach loop looks as if it might be testing whether every sequence element satisfies a predicate - consider using '.All(...)'. |
Loading