diff --git a/csharp/ql/lib/Linq/Helpers.qll b/csharp/ql/lib/Linq/Helpers.qll index 1657e812c268..69d37627ca85 100644 --- a/csharp/ql/lib/Linq/Helpers.qll +++ b/csharp/ql/lib/Linq/Helpers.qll @@ -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 @@ -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 @@ -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()) ) } @@ -132,7 +148,7 @@ private module LinqFilterOpportunity { 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) @@ -144,7 +160,7 @@ private module LinqMapOpportunity { 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*() @@ -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::missed(fes, _) and - numStmts(fes) = 1 + numStmts(fes) = 1 and + ( + LinqFilterOpportunity::missed(fes, _) + or + LinqFilterOpportunity::missed(fes, _) and + supportsLinqEarlyReturn(fes) and + returnAfterForeach(fes).getExpr().stripImplicit().(BoolLiteral).getBoolValue() = true + ) } private predicate linqCastCandidate(Stmt s, Expr e) { @@ -292,10 +328,8 @@ predicate missedFirstOrDefaultOpportunity(ForEachStmtGenericEnumerable fes, IfSt // The loop only checks whether the current element is the first match. LinqFilterOpportunity::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) } diff --git a/csharp/ql/src/change-notes/2026-11-16-missed-all-early-return.md b/csharp/ql/src/change-notes/2026-11-16-missed-all-early-return.md new file mode 100644 index 000000000000..957cc33bf0ec --- /dev/null +++ b/csharp/ql/src/change-notes/2026-11-16-missed-all-early-return.md @@ -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`. diff --git a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs index 4b09d8bd6409..e586925a8742 100644 --- a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs +++ b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs @@ -1,6 +1,8 @@ using System; using System.Linq; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; class MissedAllOpportunity { @@ -50,4 +52,156 @@ public class NonEnumerableClass { public IEnumerator GetEnumerator() => throw null; } + + private static bool ValidateReferenceChains(List references, Dictionary documents, object diagnostic, CancellationToken cancellationToken) + { + var completed = new HashSet(); + foreach (var start in references) + { + if (!ValidateReferenceChain(start, completed, documents, diagnostic, cancellationToken)) + { + return false; + } + } // $ Alert + return true; + } + + private static bool ValidateReferenceChain(string start, HashSet completed, Dictionary documents, object diagnostic, CancellationToken cancellationToken) => throw null; + + public bool ReturnFalseWithoutBraces(List lst) + { + foreach (int i in lst) + if (i % 2 != 0) + return false; // $ Alert + return true; + } + + public bool ReturnFalseAfterLoop(List lst) + { + foreach (int i in lst) + { + if (i % 2 != 0) + return false; + } + return false; + } + + public bool ExtraWorkBeforeReturningFalse(List lst) + { + foreach (int i in lst) + { + if (i % 2 != 0) + { + Console.WriteLine(i); + return false; + } + } + return true; + } + + public bool ExtraWorkAfterLoop(List lst) + { + foreach (int i in lst) + { + if (i % 2 != 0) + return false; + } + Console.WriteLine("All elements checked"); + return true; + } + + public bool ReturnFalseWithElse(List lst) + { + foreach (int i in lst) + { + if (i % 2 != 0) + return false; + else + Console.WriteLine(i); + } + return true; + } + + public bool ReturnFalseWithRefParameter(List lst, ref int x) + { + foreach (int i in lst) + { + if (i % 2 != x) + return false; + } + return true; + } + + public async Task ReturnFalseWithAwait(List lst) + { + foreach (int i in lst) + { + if (!await Task.FromResult(i % 2 == 0)) + return false; + } + return true; + } + + public bool ReturnFalseWithRefLocal(List 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 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 lst) + { + var limits = new RefLikeLimits(); + foreach (int i in lst) + { + if (i > limits[0]) + return false; + } + return true; + } + + public bool ReturnFalseWithRefLikeParameter(List lst, RefLikeLimits limits) + { + foreach (int i in lst) + { + if (i > limits[0]) + return false; + } + return true; + } + + public void AssignFalseWithRefLocal(List 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 and ReadOnlySpan. + public ref struct RefLikeLimits + { + public T this[int index] => throw null; + } } diff --git a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.expected b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.expected index b4300f8caf07..3d711bfad973 100644 --- a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.expected +++ b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.expected @@ -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(...)'. |