Skip to content

Commit

Permalink
Issue sevntu-checkstyle#882: update LogicConditionNeedOptimizationChe…
Browse files Browse the repository at this point in the history
…ck to avoid false positive
  • Loading branch information
nrmancuso authored and rnveach committed Oct 14, 2022
1 parent 9a793b3 commit 0521839
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ private static boolean needOptimization(DetailAST logicNode) {
final boolean secondTypeCast = branchContains(operands, 2, TokenTypes.TYPECAST);
final boolean result;

if (firstInstanceOf && secondTypeCast) {
if (isPatternVariableIntroduced(logicNode) || firstInstanceOf && secondTypeCast) {
result = false;
}
else {
Expand Down Expand Up @@ -190,4 +190,18 @@ private static boolean branchContains(DetailAST start, DetailAST end, int type)
return result;
}

/**
* If pattern variable is introduced, 'instanceof` must appear before condition
* that checks pattern variable.
*
* @param logicNode logic node whose children we check
* @return true if a pattern variable is introduced
*/
private static boolean isPatternVariableIntroduced(DetailAST logicNode) {
final DetailAST firstOperand = logicNode.getFirstChild();
return firstOperand.getType() == TokenTypes.LITERAL_INSTANCEOF
&& firstOperand.getLastChild() != null
&& firstOperand.getLastChild().getType() == TokenTypes.PATTERN_VARIABLE_DEF;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;

public class LogicConditionNeedOptimizationCheckTest extends AbstractModuleTestSupport {

Expand Down Expand Up @@ -66,4 +67,14 @@ public void test() throws Exception {
verify(checkConfig, getPath("InputLogicConditionNeedOptimizationCheck.java"), expected);
}

@Test
public void testJava17Patterns() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(LogicConditionNeedOptimizationCheck.class);
final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
verify(checkConfig,
getNonCompilablePath("InputLogicConditionNeedsOptimizationPatterns.java"),
expected);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.github.sevntu.checkstyle.checks.coding;

public class InputLogicConditionNeedsOptimizationPatterns {
void m1(Object o) {
for (int i = 0; o instanceof Integer myInt && myInt > 5;) { // ok
// type pattern, no `PATTERN_DEF`
}
for (int i = 0; o instanceof (Integer myInt && myInt > 5);) { // ok
// parenthesized pattern, `PATTERN_DEF`
}
for (int i = 0; o instanceof Integer myInt; ) { // ok
// type pattern, no `PATTERN_DEF`
}
}

}

0 comments on commit 0521839

Please sign in to comment.