From e1b0ffdc2f00c33aa42b5a56b749300155fc48fa Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Mon, 16 Nov 2026 13:38:45 -0500 Subject: [PATCH 1/4] 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/4] 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; + } } From 15bfe47bbc04773c203832c028287bc4a1789416 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Nov 2026 08:18:12 -0500 Subject: [PATCH 3/4] C#: Share LINQ capture and return checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9b915c45-508e-42fe-a60f-de9a6473b250 --- csharp/ql/lib/Linq/Helpers.qll | 32 ++++++++++--------- .../2026-11-16-missed-all-early-return.md | 4 --- .../MissedAllOpportunity.cs | 14 ++++++++ 3 files changed, 31 insertions(+), 19 deletions(-) delete mode 100644 csharp/ql/lib/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 4f1cce6f382a..1d6ff56873f2 100644 --- a/csharp/ql/lib/Linq/Helpers.qll +++ b/csharp/ql/lib/Linq/Helpers.qll @@ -29,10 +29,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 +129,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 +142,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 +154,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*() @@ -174,13 +184,9 @@ 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" + ret.getExpr().stripImplicit().(BoolLiteral).getBoolValue() = false ) ) } @@ -202,11 +208,7 @@ predicate missedAllOpportunity(ForEachStmtGenericEnumerable fes) { 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" - ) + returnAfterForeach(fes).getExpr().stripImplicit().(BoolLiteral).getBoolValue() = true ) } 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 deleted file mode 100644 index 22abb0ef1a36..000000000000 --- a/csharp/ql/lib/change-notes/2026-11-16-missed-all-early-return.md +++ /dev/null @@ -1,4 +0,0 @@ ---- -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/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs index bdee82c7bffd..e586925a8742 100644 --- a/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs +++ b/csharp/ql/test/query-tests/Linq/MissedAllOpportunity/MissedAllOpportunity.cs @@ -185,6 +185,20 @@ public bool ReturnFalseWithRefLikeParameter(List lst, RefLikeLimits li 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 { From 3a829bea93a6ba82a5023c17c86eb4b4bca5629a Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Nov 2026 08:56:21 -0500 Subject: [PATCH 4/4] C#: Share LINQ early-return guards Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9b915c45-508e-42fe-a60f-de9a6473b250 --- csharp/ql/lib/Linq/Helpers.qll | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/csharp/ql/lib/Linq/Helpers.qll b/csharp/ql/lib/Linq/Helpers.qll index 1d6ff56873f2..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 @@ -205,9 +211,7 @@ predicate missedAllOpportunity(ForEachStmtGenericEnumerable fes) { LinqFilterOpportunity::missed(fes, _) or LinqFilterOpportunity::missed(fes, _) and - not fes.isAsync() and - not fes.getVariable().isCaptured() and - fes.getElementType() = fes.getVariable().getType() and + supportsLinqEarlyReturn(fes) and returnAfterForeach(fes).getExpr().stripImplicit().(BoolLiteral).getBoolValue() = true ) } @@ -324,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) }