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
58 changes: 46 additions & 12 deletions csharp/ql/lib/Linq/Helpers.qll
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ private int numStmts(ForEachStmt fes) {
else result = 1
}

private predicate supportsLinqEarlyReturn(ForEachStmt fes) {
not fes.isAsync() and
not fes.getVariable().isCaptured() and
fes.getElementType() = fes.getVariable().getType()
}

private predicate returnsLoopVariable(ForEachStmt fes, Stmt s) {
exists(ReturnStmt ret |
ret = s.stripSingletonBlocks() and
Expand All @@ -29,10 +35,16 @@ private predicate returnsLoopVariable(ForEachStmt fes, Stmt s) {

private predicate hasNullDefault(Type t) { t.isRefType() or t instanceof NullableType }

private predicate returnsDefaultValueAfterForeach(ForEachStmt fes) {
exists(BlockStmt enclosingBlock, int i, Type elementType, ReturnStmt ret |
private ReturnStmt returnAfterForeach(ForEachStmt fes) {
exists(BlockStmt enclosingBlock, int i |
enclosingBlock.getStmt(i) = fes and
enclosingBlock.getStmt(i + 1) = ret and
enclosingBlock.getStmt(i + 1) = result
)
}

private predicate returnsDefaultValueAfterForeach(ForEachStmt fes) {
exists(Type elementType, ReturnStmt ret |
ret = returnAfterForeach(fes) and
elementType = fes.getVariable().getType()
|
ret.getExpr().stripImplicit() instanceof NullLiteral and
Expand Down Expand Up @@ -123,6 +135,10 @@ private predicate acceptableForLinqCapture(Expr e) {
pa = e.getAChildExpr*()
|
p.isOutOrRef() or p.isIn() or p.isReadonlyRef()
) and
not exists(LocalScopeVariable v |
v.getAnAccess() = e.getAChildExpr*() and
(v.isRef() or v.getType().isRefLikeType())
)
}

Expand All @@ -132,7 +148,7 @@ private module LinqFilterOpportunity<linqCandidateSig/2 linqCandidate> {
predicate missed(ForEachStmtGenericEnumerable fes, Stmt s) {
s = firstStmt(fes) and
// The linq candidate expression accesses the loop variable, and the
// candidate doesn't access an in, out, or ref parameter.
// candidate can be captured in a LINQ lambda.
exists(Expr candidate | linqCandidate(s, candidate) |
fes.getVariable().getAnAccess() = candidate.getAChildExpr*() and
acceptableForLinqCapture(candidate)
Expand All @@ -144,7 +160,7 @@ private module LinqMapOpportunity<linqCandidateSig/2 linqCandidate> {
predicate missed(ForEachStmt fes, Stmt s) {
s = firstStmt(fes) and
// The linq candidate (and only the candidate) expression accesses the loop variable and the
// candidate doesn't access an in, out, or ref parameter.
// candidate can be captured in a LINQ lambda.
exists(Expr candidate | linqCandidate(s, candidate) |
forex(VariableAccess va | va = fes.getVariable().getAnAccess() |
va = candidate.getAChildExpr*()
Expand All @@ -168,16 +184,36 @@ 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
exists(ReturnStmt ret |
ret = is.getThen().stripSingletonBlocks() and
ret.getExpr().stripImplicit().(BoolLiteral).getBoolValue() = 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
supportsLinqEarlyReturn(fes) and
returnAfterForeach(fes).getExpr().stripImplicit().(BoolLiteral).getBoolValue() = true
)
}

private predicate linqCastCandidate(Stmt s, Expr e) {
Expand Down Expand Up @@ -292,10 +328,8 @@ predicate missedFirstOrDefaultOpportunity(ForEachStmtGenericEnumerable fes, IfSt
// The loop only checks whether the current element is the first match.
LinqFilterOpportunity<linqFirstOrDefaultCandidate/2>::missed(fes, is) and
numStmts(fes) = 1 and
not fes.isAsync() and
not fes.getVariable().isCaptured() and
supportsLinqEarlyReturn(fes) and
returnsLoopVariable(fes, is.getThen()) and
fes.getElementType() = fes.getVariable().getType() and
returnsDefaultValueAfterForeach(fes)
}

Expand Down
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,156 @@ 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;
}

public void AssignFalseWithRefLocal(List<int> lst, ref int x)
{
ref var y = ref x;
var allEven = true;
foreach (int i in lst)
{
if (i % 2 != y)
{
allEven = false;
break;
}
}
}

// 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