Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
| test.c:7:18:7:18 | D | Type declaration D is not used. |
| test.c:28:11:28:11 | R | Type declaration R is not used. |
| test.c:41:12:41:12 | (unnamed class/struct/union) | Type declaration (unnamed class/struct/union) is not used. |
| test.c:56:3:56:4 | T2 | Type declaration T2 is not used. |
11 changes: 10 additions & 1 deletion c/common/test/rules/unusedtypedeclarations/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,13 @@ void test_nested_struct() {
s.f1;
s.f3;
s.f5;
}
}

typedef struct {
int m1;
} T2; // NON_COMPLIANT
typedef struct {
int m1;
} T1; // COMPLIANT - used in function below

void test_typedef() { T1 t1; }
6 changes: 6 additions & 0 deletions change_notes/2026-02-18-unused-type-improvements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
- `RULE-2-3`, `A0-1-6` - `UnusedTypeDeclarations.ql`:
- Type usage analysis has been improved to find more possible type usages, including:
- Previous behavior considered anonymous types in variable declarations to be considered used by the variable definition itself. This has been improved to require that a field of the anonymous type is accessed for the type to be considered used.
- Usages of a template type inside a specialization of that template are no longer considered usages of the template type.
- Hidden friend declarations are no longer considered usages of the class they are declaring friendship for.
- Improved exclusions generally, for cases such as nested types and functions within functions. These previously were a source of incorrectly identified type uses.
21 changes: 21 additions & 0 deletions cpp/common/src/codingstandards/cpp/ast/Class.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import cpp

/**
* The last declaration in a class by location order.
*
* This may fail to capture certain cases such as hidden friends (see HiddenFriend.qll).
*/
class LastClassDeclaration extends Declaration {
Class cls;

pragma[nomagic]
LastClassDeclaration() {
this =
max(Declaration decl, Location l |
decl = cls.getADeclaration() and
l = decl.getLocation()
|
decl order by l.getEndLine(), l.getEndColumn()
)
}
}
124 changes: 124 additions & 0 deletions cpp/common/src/codingstandards/cpp/ast/HiddenFriend.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* The C++ extractor does not support hidden friends, which are friend functions defined within a
* class, rather than declared:
*
* ```cpp
* struct A {
* friend void hidden_friend(A) {} // Definition: this is a hidden friend
* friend void not_hidden_friend(A); // Declaration: this is not a hidden friend
* };
* ```
*
* In the database, a `FriendDecl` is not created for the hidden friend. The hidden friend function
* is created as a `TopLevel` function with no enclosing element. However, we can identify it as a
* hidden friend by its location.
*/

import cpp
import codingstandards.cpp.ast.Class

class PossibleHiddenFriend extends HiddenFriendCandidate {
ClassCandidate cls;

PossibleHiddenFriend() { hidesFriend(cls, this) }

Class getFriendClass() { result = cls }
}

/**
* Begin by limiting the number of candidate functions to consider.
*
* Only inline top level functions can be hidden friends.
*/
private class HiddenFriendCandidate extends TopLevelFunction {
HiddenFriendCandidate() { this.isInline() }
}

/**
* Only consider files which contain hidden friend candidates.
*/
private class FileCandidate extends File {
FileCandidate() { exists(HiddenFriendCandidate c | c.getFile() = this) }
}

/**
* Only consider classes in candidate files, that include hidden friend candidates.
*/
private class ClassCandidate extends Class {
ClassCandidate() { getFile() instanceof FileCandidate }

Declaration getNextSiblingDeclaration() {
exists(LastClassDeclaration last |
last.getDeclaringType() = this and
result =
min(Declaration decl |
decl.getEnclosingElement() = this.getEnclosingElement() and
pragma[only_bind_out](decl.getFile()) = pragma[only_bind_out](this.getFile()) and
decl.getLocation().getStartLine() > last.getLocation().getEndLine()
|
decl order by decl.getLocation().getStartLine(), decl.getLocation().getStartColumn()
)
)
}

Declaration getNextOrphanedDeclaration() {
exists(LastClassDeclaration last |
last.getDeclaringType() = this and
result =
min(OrphanedDeclaration decl, Location locLast, Location locDecl |
orphanHasFile(decl, this.getFile()) and
locDecl = decl.getLocation() and
locLast = last.getLocation() and
locLast.getStartLine() < locDecl.getEndLine()
|
decl order by locDecl.getStartLine(), locDecl.getStartColumn()
)
)
}

Declaration getFirstNonClassDeclaration() {
exists(LastClassDeclaration last |
last.getDeclaringType() = this and
result =
min(Declaration decl |
decl = getNextSiblingDeclaration() or decl = getNextOrphanedDeclaration()
|
decl order by decl.getLocation().getStartLine(), decl.getLocation().getStartColumn()
)
)
}
}

pragma[nomagic]
private predicate orphanHasFile(OrphanedDeclaration orphan, FileCandidate file) {
orphan.getFile() = file
}

private class OrphanedDeclaration extends Declaration {
OrphanedDeclaration() {
not exists(getEnclosingElement()) and
not this instanceof HiddenFriendCandidate and
getFile() instanceof FileCandidate and
not isFromTemplateInstantiation(_)
}
}

pragma[nomagic]
private predicate classCandidateHasFile(ClassCandidate c, FileCandidate f) { c.getFile() = f }

pragma[nomagic]
private predicate hiddenFriendCandidateHasFile(HiddenFriendCandidate h, FileCandidate f) {
h.getFile() = f
}

pragma[nomagic]
private predicate hidesFriend(ClassCandidate c, HiddenFriendCandidate f) {
exists(FileCandidate file, Location cloc, Location floc |
classCandidateHasFile(c, file) and
hiddenFriendCandidateHasFile(f, file) and
cloc = c.getLocation() and
floc = f.getLocation() and
cloc.getEndLine() < floc.getStartLine() and
floc.getEndLine() < c.getFirstNonClassDeclaration().getLocation().getStartLine()
)
}
26 changes: 26 additions & 0 deletions cpp/common/src/codingstandards/cpp/exclusions/cpp/DeadCode9.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//** THIS FILE IS AUTOGENERATED, DO NOT MODIFY DIRECTLY. **/
import cpp
import RuleMetadata
import codingstandards.cpp.exclusions.RuleMetadata

newtype DeadCode9Query = TUnusedTypeWithLimitedVisibilityQuery()

predicate isDeadCode9QueryMetadata(Query query, string queryId, string ruleId, string category) {
query =
// `Query` instance for the `unusedTypeWithLimitedVisibility` query
DeadCode9Package::unusedTypeWithLimitedVisibilityQuery() and
queryId =
// `@id` for the `unusedTypeWithLimitedVisibility` query
"cpp/misra/unused-type-with-limited-visibility" and
ruleId = "RULE-0-2-3" and
category = "advisory"
}

module DeadCode9Package {
Query unusedTypeWithLimitedVisibilityQuery() {
//autogenerate `Query` type
result =
// `Query` type for `unusedTypeWithLimitedVisibility` query
TQueryCPP(TDeadCode9PackageQuery(TUnusedTypeWithLimitedVisibilityQuery()))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import Conversions2
import DeadCode
import DeadCode3
import DeadCode4
import DeadCode9
import Declarations
import ExceptionSafety
import Exceptions1
Expand Down Expand Up @@ -91,6 +92,7 @@ newtype TCPPQuery =
TDeadCodePackageQuery(DeadCodeQuery q) or
TDeadCode3PackageQuery(DeadCode3Query q) or
TDeadCode4PackageQuery(DeadCode4Query q) or
TDeadCode9PackageQuery(DeadCode9Query q) or
TDeclarationsPackageQuery(DeclarationsQuery q) or
TExceptionSafetyPackageQuery(ExceptionSafetyQuery q) or
TExceptions1PackageQuery(Exceptions1Query q) or
Expand Down Expand Up @@ -163,6 +165,7 @@ predicate isQueryMetadata(Query query, string queryId, string ruleId, string cat
isDeadCodeQueryMetadata(query, queryId, ruleId, category) or
isDeadCode3QueryMetadata(query, queryId, ruleId, category) or
isDeadCode4QueryMetadata(query, queryId, ruleId, category) or
isDeadCode9QueryMetadata(query, queryId, ruleId, category) or
isDeclarationsQueryMetadata(query, queryId, ruleId, category) or
isExceptionSafetyQueryMetadata(query, queryId, ruleId, category) or
isExceptions1QueryMetadata(query, queryId, ruleId, category) or
Expand Down
38 changes: 37 additions & 1 deletion cpp/common/src/codingstandards/cpp/types/Uses.qll
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
*/

import cpp
import codingstandards.cpp.ast.HiddenFriend

/**
* Gets a typedef with the same qualified name and declared at the same location.
Expand All @@ -35,7 +36,8 @@ private TypedefType getAnEquivalentTypeDef(TypedefType type) {
* is from within the function signature or field declaration of the type itself.
*/
Locatable getATypeUse(Type type) {
result = getATypeUse_i(type, _)
result = getATypeUse_i(type, _) and
not isWithinTypeDefinition(result, type)
or
// Identify `TypeMention`s of typedef types, where the underlying type is used.
//
Expand Down Expand Up @@ -65,6 +67,39 @@ Locatable getATypeUse(Type type) {
)
}

predicate isWithinTypeDefinition(Locatable loc, Type type) {
loc = type
or
loc.getEnclosingElement*() = type
or
isWithinTypeDefinition(loc.(Function).getDeclaringType(), type)
or
isWithinTypeDefinition(loc.(MemberVariable).getDeclaringType(), type)
or
isWithinTypeDefinition(loc.(PossibleHiddenFriend).getFriendClass(), type)
or
isWithinTypeDefinition(loc.(Parameter).getFunction(), type)
or
isWithinTypeDefinition(loc.(Expr).getEnclosingFunction(), type)
or
isWithinTypeDefinition(loc.(LocalVariable).getFunction(), type)
or
exists(TemplateClass tpl, ClassTemplateSpecialization spec |
tpl = type and
tpl = spec.getPrimaryTemplate() and
isWithinTypeDefinition(loc, spec)
)
//exists(TemplateClass tpl, ClassTemplateSpecialization spec |
// tpl.getAnInstantiation() = type and
// tpl = spec.getPrimaryTemplate() and
// isWithinTypeDefinition(loc, spec)
//)
//exists(ClassTemplateSpecialization spec |
// specializationSharesType(type, spec) and
// isWithinTypeDefinition(loc, spec)
//)
Comment on lines +92 to +100
Copy link

Copilot AI Feb 18, 2026

Choose a reason for hiding this comment

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

There is commented-out code in the isWithinTypeDefinition predicate (lines 92-100). If this code is no longer needed, it should be removed. If it's being kept for future reference or debugging, a comment should be added explaining why it's commented out and whether it will be used in the future.

Suggested change
//exists(TemplateClass tpl, ClassTemplateSpecialization spec |
// tpl.getAnInstantiation() = type and
// tpl = spec.getPrimaryTemplate() and
// isWithinTypeDefinition(loc, spec)
//)
//exists(ClassTemplateSpecialization spec |
// specializationSharesType(type, spec) and
// isWithinTypeDefinition(loc, spec)
//)

Copilot uses AI. Check for mistakes.
}

private Locatable getATypeUse_i(Type type, string reason) {
(
// Restrict to uses within the source checkout root
Expand All @@ -81,6 +116,7 @@ private Locatable getATypeUse_i(Type type, string reason) {
type = v.getType() and
// Ignore self referential variables and parameters
not v.getDeclaringType().refersTo(type) and
not type.(UserType).isAnonymous() and
not type = v.(Parameter).getFunction().getDeclaringType()
) and
reason = "used as a variable type"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
| test.cpp:77:11:77:11 | R | Type declaration R is not used. |
| test.cpp:90:12:90:12 | (unnamed class/struct/union) | Type declaration (unnamed class/struct/union) is not used. |
| test.cpp:111:29:111:30 | AA | Type declaration AA is not used. |
| test.cpp:126:7:126:12 | Nested | Type declaration Nested is not used. |
| test.cpp:135:9:135:20 | UnusedNested | Type declaration UnusedNested is not used. |
| test.cpp:138:7:138:22 | NestedBlockScope | Type declaration NestedBlockScope is not used. |
| test.cpp:149:11:149:16 | Unused | Type declaration Unused is not used. |
29 changes: 28 additions & 1 deletion cpp/common/test/rules/unusedtypedeclarations/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,31 @@ void test_temporary_object_creation() {

return C1{p1};
};
}
}

class Nested { // NON_COMPLIANT - only used within itself
public:
class NestedNested { // COMPLIANT - used by class `Nested`
public:
Nested f();
};

NestedNested g();

class UnusedNested {}; // NON_COMPLIANT - never used by class `Nested`
};

class NestedBlockScope { // NON_COMPLIANT - only used within itself
public:
void f() {
class NestedFunction { // COMPLIANT - used in function below
void g() {
NestedBlockScope l1; // Doesn't count as use of `NestedBlockScope`.
}
};

NestedFunction l1;

class Unused {}; // NON_COMPLIANT - never used by function `f`
}
};
38 changes: 38 additions & 0 deletions cpp/misra/src/rules/RULE-0-2-3/UnusedTypeWithLimitedVisibility.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @id cpp/misra/unused-type-with-limited-visibility
* @name RULE-0-2-3: Types with limited visibility should be used at least once
* @description Types that are unused with limited visibility are unnecessary and should either be
* removed or may indicate a developer mistake.
* @kind problem
* @precision very-high
* @problem.severity error
* @tags external/misra/id/rule-0-2-3
* scope/single-translation-unit
* maintainability
* correctness
* external/misra/enforcement/decidable
* external/misra/obligation/advisory
*/

import cpp
import codingstandards.cpp.misra
import codingstandards.cpp.types.Uses

predicate hasLimitedVisibility(UserType type) {
type.isLocal() or
type.getNamespace().isAnonymous()
}

predicate hasMaybeUnusedAttribute(UserType type) {
exists(Attribute a | a = type.getAnAttribute() and a.getName() = "maybe_unused")
}

from UserType type
where
not isExcluded(type, DeadCode9Package::unusedTypeWithLimitedVisibilityQuery()) and
hasLimitedVisibility(type) and
not exists(getATypeUse(type)) and
not hasMaybeUnusedAttribute(type) and
not type instanceof TypeTemplateParameter and
not type instanceof ClassTemplateSpecialization
select type, "Type '" + type.getName() + "' with limited visibility is not used."
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
| test.cpp:5:9:5:10 | T1 | Type 'T1' with limited visibility is not used. |
| test.cpp:22:8:22:9 | A1 | Type 'A1' with limited visibility is not used. |
| test.cpp:26:8:26:9 | A2 | Type 'A2' with limited visibility is not used. |
| test.cpp:62:28:62:29 | C1<<unnamed>> | Type 'C1<<unnamed>>' with limited visibility is not used. |
| test.cpp:79:14:79:14 | (unnamed class/struct/union) | Type '(unnamed class/struct/union)' with limited visibility is not used. |
| test.cpp:105:12:105:13 | E2 | Type 'E2' with limited visibility is not used. |
| test.cpp:115:9:115:10 | T2 | Type 'T2' with limited visibility is not used. |
| test.cpp:126:10:126:11 | S2 | Type 'S2' with limited visibility is not used. |
| test.cpp:133:8:133:9 | A3 | Type 'A3' with limited visibility is not used. |
| test.cpp:145:8:145:9 | A6 | Type 'A6' with limited visibility is not used. |
| test.cpp:152:29:152:42 | AliasTemplate1 | Type 'AliasTemplate1' with limited visibility is not used. |
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rules/RULE-0-2-3/UnusedTypeWithLimitedVisibility.ql
Loading
Loading