@@ -20,15 +20,19 @@ private int numStmts(ForeachStmt fes) {
2020 else result = 1
2121}
2222
23- private predicate returnsLoopVariable ( ForeachStmt fes , Stmt s , ReturnStmt ret ) {
24- ret = s .stripSingletonBlocks ( ) and
25- ret .getExpr ( ) .stripCasts ( ) .( VariableAccess ) .getTarget ( ) = fes .getVariable ( )
23+ private predicate returnsLoopVariable ( ForeachStmt fes , Stmt s ) {
24+ exists ( ReturnStmt ret |
25+ ret = s .stripSingletonBlocks ( ) and
26+ ret .getExpr ( ) .stripCasts ( ) .( VariableAccess ) .getTarget ( ) = fes .getVariable ( )
27+ )
2628}
2729
2830private predicate hasNullDefault ( Type t ) { t .isRefType ( ) or t instanceof NullableType }
2931
30- private predicate returnsDefaultValue ( ForeachStmt fes , ReturnStmt ret ) {
31- exists ( Type elementType |
32+ private predicate returnsDefaultValueAfterForeach ( ForeachStmt fes ) {
33+ exists ( BlockStmt enclosingBlock , int i , Type elementType , ReturnStmt ret |
34+ enclosingBlock .getStmt ( i ) = fes and
35+ enclosingBlock .getStmt ( i + 1 ) = ret and
3236 elementType = fes .getVariable ( ) .getType ( )
3337 |
3438 ret .getExpr ( ) .stripCasts ( ) instanceof NullLiteral and
@@ -192,18 +196,14 @@ predicate missedFirstOrDefaultOpportunity(ForeachStmtGenericEnumerable fes, IfSt
192196 is = firstStmt ( fes ) and
193197 not exists ( is .getElse ( ) ) and
194198 numStmts ( fes ) = 1 and
199+ // Condition relies on loop variable.
195200 exists ( VariableAccess va |
196201 va .getTarget ( ) = fes .getVariable ( ) and
197202 va = is .getCondition ( ) .getAChildExpr * ( )
198203 ) and
199204 not is .getCondition ( ) .getAChildExpr * ( ) instanceof AwaitExpr and
200- exists ( ReturnStmt ret , ReturnStmt defaultRet , BlockStmt enclosingBlock , int i |
201- returnsLoopVariable ( fes , is .getThen ( ) , ret ) and
202- // If no element matches, the method returns the same value that FirstOrDefault would.
203- returnsDefaultValue ( fes , defaultRet ) and
204- enclosingBlock .getStmt ( i ) = fes and
205- enclosingBlock .getStmt ( i + 1 ) = defaultRet
206- )
205+ returnsLoopVariable ( fes , is .getThen ( ) ) and
206+ returnsDefaultValueAfterForeach ( fes )
207207}
208208
209209//#################### CLASSES ####################
0 commit comments