Skip to content

Commit 54d01bd

Browse files
authored
Merge pull request #1648 from hvitved/csharp/unchecked-return-lambda
C#: Fix false positives in `cs/unchecked-return-value`
2 parents b03cf6f + 5c127ef commit 54d01bd

File tree

4 files changed

+31
-2
lines changed

4 files changed

+31
-2
lines changed

change-notes/1.22/analysis-csharp.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
| Number of commits | No results | Query has been removed. |
2525
| Poorly documented files with many authors | No results | Query has been removed. |
2626
| Recent activity | No results | Query has been removed. |
27+
| Unchecked return value (`cs/unchecked-return-value`) | Fewer false positive results | Method calls that are expression bodies of `void` callables (for example, the call to `Foo` in `void Bar() => Foo()`) are no longer considered to use the return value. |
2728

2829
## Changes to code extraction
2930

csharp/ql/src/API Abuse/UncheckedReturnValue.ql

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,14 @@ predicate whitelist(Method m) {
8989
}
9090

9191
class DiscardedMethodCall extends MethodCall {
92-
DiscardedMethodCall() { this.getParent() instanceof ExprStmt }
92+
DiscardedMethodCall() {
93+
this.getParent() instanceof ExprStmt
94+
or
95+
exists(Callable c |
96+
this = c.getExpressionBody() and
97+
not c.canReturn(this)
98+
)
99+
}
93100

94101
string query() {
95102
exists(Method m |

csharp/ql/src/semmle/code/csharp/Callable.qll

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,8 @@ class Callable extends DotNet::Callable, Parameterizable, ExprOrStmtParent, @cal
209209
override predicate canReturn(DotNet::Expr e) {
210210
exists(ReturnStmt ret | ret.getEnclosingCallable() = this | e = ret.getExpr())
211211
or
212-
e = getExpressionBody()
212+
e = this.getExpressionBody() and
213+
not this.getReturnType() instanceof VoidType
213214
}
214215

215216
/** Holds if this callable can yield return the expression `e`. */

csharp/ql/test/query-tests/API Abuse/UncheckedReturnValue/UncheckedReturnValue.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,23 @@ class C5 { }
158158
class C6 : C5 { }
159159
class C7 : C6 { }
160160
}
161+
162+
class C5
163+
{
164+
int M1() => 0;
165+
166+
void M2()
167+
{
168+
// GOOD
169+
M1();
170+
Action a = () => M1();
171+
a = () => M1();
172+
a = () => M1();
173+
a = () => M1();
174+
a = () => M1();
175+
a = () => M1();
176+
a = () => M1();
177+
a = () => M1();
178+
a = () => M1();
179+
}
180+
}

0 commit comments

Comments
 (0)