@@ -18,10 +18,10 @@ import cpp
1818import codingstandards.cpp.autosar
1919import codingstandards.cpp.deadcode.UnusedVariables
2020
21- /** Gets the constant value of a constexpr variable. */
21+ /** Gets the constant value of a constexpr/const variable. */
2222private string getConstExprValue ( Variable v ) {
2323 result = v .getInitializer ( ) .getExpr ( ) .getValue ( ) and
24- v . isConstexpr ( )
24+ ( v . isConst ( ) or v . isConstexpr ( ) )
2525}
2626
2727// This predicate is similar to getUseCount for M0-1-4 except that it also
@@ -41,13 +41,28 @@ int getUseCountConservatively(Variable v) {
4141 ) +
4242 // For static asserts too, check if there is a child which has the same value
4343 // as the constexpr variable.
44- count ( StaticAssert s | s .getCondition ( ) .getAChild * ( ) .getValue ( ) = getConstExprValue ( v ) )
44+ count ( StaticAssert s | s .getCondition ( ) .getAChild * ( ) .getValue ( ) = getConstExprValue ( v ) ) +
45+ // In case an array type uses a constant in the same scope as the constexpr variable,
46+ // consider it as used.
47+ count ( ArrayType at , LocalVariable arrayVariable |
48+ arrayVariable .getType ( ) .resolveTypedefs ( ) = at and
49+ v .( PotentiallyUnusedLocalVariable ) .getFunction ( ) = arrayVariable .getFunction ( ) and
50+ at .getArraySize ( ) .toString ( ) = getConstExprValue ( v )
51+ )
4552}
4653
4754from PotentiallyUnusedLocalVariable v
4855where
4956 not isExcluded ( v , DeadCodePackage:: unusedLocalVariableQuery ( ) ) and
5057 // Local variable is never accessed
5158 not exists ( v .getAnAccess ( ) ) and
59+ // Sometimes multiple objects representing the same entities are created in
60+ // the AST. Check if those are not accessed as well. Refer issue #658
61+ not exists ( LocalScopeVariable another |
62+ another .getDefinitionLocation ( ) = v .getDefinitionLocation ( ) and
63+ another .hasName ( v .getName ( ) ) and
64+ exists ( another .getAnAccess ( ) ) and
65+ another != v
66+ ) and
5267 getUseCountConservatively ( v ) = 0
5368select v , "Local variable '" + v .getName ( ) + "' in '" + v .getFunction ( ) .getName ( ) + "' is not used."
0 commit comments