Skip to content

Commit cce11f4

Browse files
committed
DeadCode: Add MISRA C 2012 Rule 2.5
Adds a query to find unused macro declarations. The query is mostly straightforward, however #undefs are not connected in our database schema with the #defines they undefine. This means that we cannot accurately identify unused macros when there is a sequence of defs and undefs.
1 parent 87a1780 commit cce11f4

File tree

5 files changed

+50
-0
lines changed

5 files changed

+50
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @id c/misra/unused-macro-declaration
3+
* @name RULE-2-5: A project should not contain unused macro declarations
4+
* @description Unused macro declarations are either redundant or indicate a possible mistake on the
5+
* part of the programmer.
6+
* @kind problem
7+
* @precision very-high
8+
* @problem.severity warning
9+
* @tags external/misra/id/rule-2-5
10+
* readability
11+
* maintainability
12+
* external/misra/obligation/advisory
13+
*/
14+
15+
import cpp
16+
import codingstandards.c.misra
17+
18+
from Macro m
19+
where
20+
not isExcluded(m, DeadCodePackage::unusedMacroDeclarationQuery()) and
21+
not exists(MacroAccess ma | ma.getMacro() = m) and
22+
// We consider a macro "used" if the name is undef-ed at some point in the same file, or a file
23+
// that includes the file defining the macro. This will over approximate use in the case of a
24+
// macro which is defined, then undefined, then re-defined but not used.
25+
not exists(PreprocessorUndef u |
26+
u.getName() = m.getName() and u.getFile().getAnIncludedFile*() = m.getFile()
27+
)
28+
select m, "Macro " + m.getName() + " is unused."
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
| test.c:4:1:4:16 | #define MACRO3 3 | Macro MACRO3 is unused. |
2+
| test.h:3:1:3:21 | #define HEADER_MACRO3 | Macro HEADER_MACRO3 is unused. |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
rules/RULE-2-5/UnusedMacroDeclaration.ql

c/misra/test/rules/RULE-2-5/test.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include "test.h"
2+
#define MACRO1 1 // COMPLIANT
3+
#define MACRO2 2 // COMPLIANT
4+
#define MACRO3 3 // NON_COMPLIANT
5+
6+
#undef MACRO1
7+
8+
// This case is not captured by the query
9+
#define MACRO1 1 // NON_COMPLIANT[FALSE_NEGATIVE]
10+
11+
#undef HEADER_MACRO1
12+
13+
void test() {
14+
MACRO2;
15+
HEADER_MACRO2;
16+
}

c/misra/test/rules/RULE-2-5/test.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#define HEADER_MACRO1 // COMPLIANT
2+
#define HEADER_MACRO2 // COMPLIANT
3+
#define HEADER_MACRO3 // NON_COMPLIANT

0 commit comments

Comments
 (0)