From e1b0ffdc2f00c33aa42b5a56b749300155fc48fa Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 16 Nov 2026 13:38:45 -0500 Subject: [PATCH 1/2] C#: Fix missed All opportunities with early returns Recognize foreach loops that return false on a failed condition and return true immediately after the loop. Add regression coverage and change notes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b48b187b-dcc1-4a8b-a428-b9ee51f638f4 --- csharp/ql/lib/Linq/Helpers.qll | 34 ++++++- .../2026-11-16-missed-all-early-return.md | 4 + .../2026-11-16-missed-all-early-return.md | 4 + .../MissedAllOpportunity.cs | 91 +++++++++++++++++++ .../MissedAllOpportunity.expected | 4 +- 5 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 csharp/ql/lib/change-notes/2026-11-16-missed-all-early-return.md create mode 100644 csharp/ql/src/change-notes/2026-11-16-missed-all-early-return.md diff --git a/csharp/ql/lib/Linq/Helpers.qll b/csharp/ql/lib/Linq/Helpers.qll index 1657e812c268..bdd07e325849 100644 --- a/csharp/ql/lib/Linq/Helpers.qll +++ b/csharp/ql/lib/Linq/Helpers.qll @@ -168,16 +168,42 @@ 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).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::missed(fes, _) and - numStmts(fes) = 1 + numStmts(fes) = 1 and + ( + LinqFilterOpportunity::missed(fes, _) + or + LinqFilterOpportunity::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) { diff --git a/csharp/ql/lib/change-notes/2026-11-16-missed-all-early-return.md b/csharp/ql/lib/change-notes/2026-11-16-missed-all-early-return.md new file mode 100644 index 000000000000..22abb0ef1a36 --- /dev/null +++ b/csharp/ql/lib/change-notes/2026-11-16-missed-all-early-return.md @@ -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`. 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..78b73439a3d9 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,93 @@ 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; + } } 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(...)'. | From a41b26528b53e7f2e77f01f84a659942f4ab8aa5 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 16 Nov 2026 13:58:06 -0500 Subject: [PATCH 2/2] C#: Fix ref captures in early-return All suggestions Exclude ref locals and ref-like locals or parameters from the new All candidate path. Add negative regressions for ref and ref readonly locals and generic ref-struct locals and parameters. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b48b187b-dcc1-4a8b-a428-b9ee51f638f4 --- csharp/ql/lib/Linq/Helpers.qll | 4 ++ .../MissedAllOpportunity.cs | 49 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/csharp/ql/lib/Linq/Helpers.qll b/csharp/ql/lib/Linq/Helpers.qll index bdd07e325849..4f1cce6f382a 100644 --- a/csharp/ql/lib/Linq/Helpers.qll +++ b/csharp/ql/lib/Linq/Helpers.qll @@ -174,6 +174,10 @@ private predicate linqAllReturnCandidate(Stmt s, Expr e) { 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" diff --git a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs index 78b73439a3d9..bdee82c7bffd 100644 --- a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs +++ b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs @@ -141,4 +141,53 @@ public async Task ReturnFalseWithAwait(List lst) } 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; + } + + // Framework stubs omit the ref modifier on Span and ReadOnlySpan. + public ref struct RefLikeLimits + { + public T this[int index] => throw null; + } }