|
| 1 | +/** |
| 2 | + * @name Non-final immutable field |
| 3 | + * @description A field of immutable type that is assigned to only in a constructor or static |
| 4 | + * initializer of its declaring type, but is not declared 'final', may lead to defects |
| 5 | + * and makes code less readable. |
| 6 | + * @kind problem |
| 7 | + * @problem.severity recommendation |
| 8 | + * @precision medium |
| 9 | + * @id java/non-final-immutable-field |
| 10 | + * @tags reliability |
| 11 | + */ |
| 12 | +import java |
| 13 | + |
| 14 | +class Initialization extends Callable { |
| 15 | + Initialization() { |
| 16 | + this instanceof Constructor or |
| 17 | + this instanceof InitializerMethod |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +/** A binary or unary assignment. */ |
| 22 | +class AnyAssignment extends Expr { |
| 23 | + AnyAssignment() { |
| 24 | + this instanceof Assignment or |
| 25 | + this instanceof UnaryAssignExpr |
| 26 | + } |
| 27 | + |
| 28 | + /** The expression modified by this assignment. */ |
| 29 | + Expr getDest() { |
| 30 | + this.(Assignment).getDest() = result or |
| 31 | + this.(UnaryAssignExpr).getExpr() = result |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class ImmutableField extends Field { |
| 36 | + ImmutableField() { |
| 37 | + this.fromSource() and |
| 38 | + not this instanceof EnumConstant and |
| 39 | + this.getType() instanceof ImmutableType and |
| 40 | + // The field is only assigned to in a constructor or static initializer of the type it is declared in. |
| 41 | + forall(FieldAccess fw, AnyAssignment ae | |
| 42 | + fw.getField().getSourceDeclaration() = this and |
| 43 | + fw = ae.getDest() |
| 44 | + | ae.getEnclosingCallable().getDeclaringType() = this.getDeclaringType() and |
| 45 | + ae.getEnclosingCallable() instanceof Initialization |
| 46 | + ) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +from ImmutableField f |
| 51 | +where not f.isFinal() |
| 52 | +select f, "This immutable field is not declared final but is only assigned to during initialization." |
0 commit comments