Skip to content
Open

Gci82 #185

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- [#122](https://github.com/green-code-initiative/creedengo-java/issues/122) GCI82 - remove false positive triggered on pattern variables of `instanceof`, record patterns and `switch` patterns (e.g. `if (o instanceof final String s)`)
- [#69](https://github.com/green-code-initiative/creedengo-java/issues/69) correction of NullPointer in GCI79 rule + technical refactoring of GCI79
- update integration tests system to use the new component "creedengo-integration-test"
- compatibility updates for SonarQube up to 26.2.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ public void parameterReassigned(String reassigned) {
logger.info(reassigned);
}

public void parameterNotReassignedInstance() {
final Object o = new Object();
// instanceof with final keyword - Compliant (pattern variable is skipped)
if (o instanceof final String k) {
logger.info(k);
}
}

public void parameterNotReassigned(final String notReassigned) {
logger.info(notReassigned);
}
Expand Down Expand Up @@ -107,13 +115,13 @@ void reassignedInMethod() {
String varDefinedInMethodReassignedInMethod = "0"; // Compliant
String varDefinedInMethodInFinalMethod = "0"; // Noncompliant {{The variable is never reassigned and can be 'final'}}
String varDefinedInMethodNotReassignedInMethod = "0"; // Compliant (the String was passed as a non-final parameter to the method)

this.parameterReassigned(varDefinedInMethodReassignedInMethod);
this.parameterReassigned(this.varDefinedInClassReassignedInMethod);
this.parameterNotReassigned(varDefinedInMethodInFinalMethod);
this.parameterNotReassigned(this.varDefinedInClassInFinalMethod);
this.parameterNotReassignedNotFinal(varDefinedInMethodNotReassignedInMethod);
this.parameterNotReassignedNotFinal(this.varDefinedInClassNotReassignedInMethod);
this.parameterNotReassignedInstance();// Compliant
}

void reassignedInConstructor(){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ public List<Kind> nodesToVisit() {
@Override
public void visitNode(@Nonnull Tree tree) {
VariableTree variableTree = (VariableTree) tree;

// Issue #122 : skip pattern variables (instanceof pattern, record pattern, switch pattern).
// Pattern variables are scope-limited to their branch and cannot meaningfully be made
// "more final". SonarJava does not consistently expose the `final` modifier on pattern
// variables, which would produce a false positive when the user has explicitly written
// `final` — e.g. `if (o instanceof final String s)`.
if (isPatternVariable(variableTree)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the issue is to detect the type pattern variable when it's finak in order to not trigger an issue.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En Java, le pattern matching pour instanceof (JEP 394, finalisé en JDK 16) introduit la notion de pattern variable, qui est sémantiquement traitée comme une variable locale au sens de la JLS §14.30.1. Comme toute variable locale, elle peut recevoir les modificateurs autorisés sur les locales — dont final — qui sont définis par la JLS §4.12.4 comme une contrainte vérifiée à la compilation (interdiction de réassigner après l'initialisation). Du côté JVM, la JVMS §2.6.1 décrit le tableau des variables locales d'une stack frame comme stockant uniquement des slots typés indexés, sans aucun flag de modificateur. La JVMS §4.7.13 (attribut LocalVariableTable) confirme explicitement la structure du class file pour les variables locales : start_pc, length, name_index, descriptor_index, index — aucun champ access_flags n'existe pour les variables locales, contrairement aux classes, champs et méthodes. Conséquence directe et vérifiable : compiler if (o instanceof String s) et if (o instanceof final String s) produit strictement le même bytecode ; la présence de final ne se traduit par aucun octet supplémentaire ni aucune information runtime, donc zéro impact mémoire, zéro impact CPU à l'exécution. Pousser un développeur à ajouter final sur une pattern variable est donc une modification de code source à coût énergétique runtime nul — exactement ce qu'un linter Green Code doit éviter.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conclusion :
Le gain runtime côté application est nul, donc appliquer la règle aux pattern variables n’a pas de valeur Green IT mesurable. Par conséquent, éviter complètement leur analyse est plus cohérent sémantiquement et plus efficace algorithmiquement pour l’analyseur.

return;
}

if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Variable > {}", getVariableNameForLogger(variableTree));
LOGGER.debug(" => isNotFinalAndNotStatic(variableTree) = {}", isNotFinalAndNotStatic(variableTree));
Expand All @@ -39,6 +49,21 @@ public void visitNode(@Nonnull Tree tree) {
}
}

/**
* Returns {@code true} when the given variable is a pattern variable, i.e. it is the variable
* bound by a type pattern in:
* <ul>
* <li>an {@code instanceof} pattern: {@code if (o instanceof String s)}</li>
* <li>a record pattern component: {@code if (p instanceof Point(int x, int y))}</li>
* <li>a switch pattern: {@code case String s -> ...}</li>
* </ul>
* In all those cases, the {@code VariableTree} is the direct child of a {@code TypePatternTree}.
*/
private static boolean isPatternVariable(VariableTree variableTree) {
Tree parent = variableTree.parent();
return parent != null && parent.is(Kind.TYPE_PATTERN);
}

private static boolean isNotReassigned(VariableTree variableTree) {
return variableTree.symbol()
.usages()
Expand Down