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; }
7 changes: 7 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,7 @@
- `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.
- Additional case added to detect `template <Enum = Enum::Value>` as a usage of `Enum`, without an explicit `tpl<Enum::Value>` usage.
28 changes: 28 additions & 0 deletions cpp/common/src/codingstandards/cpp/ast/Class.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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() {
cls.getADeclaration() = this and
getLocation().getEndLine() = getLastLineOfClassDeclaration(cls)
}
}

/**
* Gets the line number of the last line of the declaration of `cls`.
*
* This is often more performant to use than `LastClassDeclaration.getLocation().getEndLine()`.
*/
int getLastLineOfClassDeclaration(Class cls) {
result =
max(int endLine |
endLine = pragma[only_bind_out](cls).getADeclaration().getLocation().getEndLine()
)
}
165 changes: 165 additions & 0 deletions cpp/common/src/codingstandards/cpp/ast/HiddenFriend.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
/**
* 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

/**
* A class that, by our best logic, appears to possibly be a hidden friend.
*
* Hidden friends are not directly represented in the database. Instances of this class have been
* found to have a location "within" the "body" of a class, and to satisfy other criteria that
* indicates it may be a hidden friend.
*/
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 }

/**
* Find the next declaration after this class that shares an enclosing element.
*
* This may be the next declaration after this class, or `getNextOrphanedDeclaration` may find the
* true next declaration after this class. These are split for performance reasons.
*/
Declaration getNextSiblingDeclaration() {
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() > getLastLineOfClassDeclaration(this)
|
decl order by decl.getLocation().getStartLine(), decl.getLocation().getStartColumn()
)
}

/**
* Get the next declaration after this class that does not have an enclosing element.
*
* This may be the next declaration after this class, or `getNextSiblingDeclaration` may find the
* true next declaration after this class. These are split for performance reasons.
*
* Note that `OrphanedDeclaration` excludes hidden friend candidates, so this will find the next
* orphan that is definitely not a hidden friend.
*/
Declaration getNextOrphanedDeclaration() {
result =
min(OrphanedDeclaration decl, int startLine, int startColumn |
orphanHasLocation(decl, this.getFile(), startLine, startColumn) and
startLine > getLastLineOfClassDeclaration(this)
|
decl order by startLine, startColumn
)
}

/**
* Get the first declaration definitely after this class, and not a hidden friend declaration, to
* determine the "end" location of this class.
*/
Declaration getFirstNonClassDeclaration() {
result =
min(Declaration decl |
decl = getNextSiblingDeclaration() or decl = getNextOrphanedDeclaration()
|
decl order by decl.getLocation().getStartLine(), decl.getLocation().getStartColumn()
)
}
}

/**
* Helper predicate to improve join performance.
*/
pragma[nomagic]
private predicate orphanHasLocation(
OrphanedDeclaration orphan, FileCandidate file, int startLine, int startColumn
) {
orphan.getFile() = file and
orphan.getLocation().getEndLine() = startLine and
orphan.getLocation().getEndColumn() = startColumn
}

/**
* Orphaned declarations to be found by `getNextOrphanedDeclaration`.
*
* These are declarations with no enclosing element. Note that we exclude hidden friend candidates,
* as this class is used to find the declarations that are definitely not part of some class. This
* is done so we can detect if hidden friends may be within that class definition. Therefore we must
* exclude hidden friend candidates, even though those are also orphaned.
*/
private class OrphanedDeclaration extends Declaration {
OrphanedDeclaration() {
not exists(getEnclosingElement()) and
not this instanceof HiddenFriendCandidate and
getFile() instanceof FileCandidate and
not isFromTemplateInstantiation(_)
}
}

/**
* Helper predicate to improve join performance.
*/
pragma[nomagic]
private predicate classCandidateHasFile(ClassCandidate c, FileCandidate f) { c.getFile() = f }

/**
* Helper predicate to improve join performance.
*/
pragma[nomagic]
private predicate hiddenFriendCandidateHasFile(HiddenFriendCandidate h, FileCandidate f) {
h.getFile() = f
}

/**
* Find the class locations that have declarations that could be hidden friend declarations, by
* comparing the locations of the candidate hidden friend functions to the location of the first
* declaration that clearly is outside that class.
*/
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 @@ -23,6 +23,7 @@ import DeadCode4
import DeadCode5
import DeadCode6
import DeadCode7
import DeadCode9
import Declarations
import ExceptionSafety
import Exceptions1
Expand Down Expand Up @@ -101,6 +102,7 @@ newtype TCPPQuery =
TDeadCode5PackageQuery(DeadCode5Query q) or
TDeadCode6PackageQuery(DeadCode6Query q) or
TDeadCode7PackageQuery(DeadCode7Query q) or
TDeadCode9PackageQuery(DeadCode9Query q) or
TDeclarationsPackageQuery(DeclarationsQuery q) or
TExceptionSafetyPackageQuery(ExceptionSafetyQuery q) or
TExceptions1PackageQuery(Exceptions1Query q) or
Expand Down Expand Up @@ -179,6 +181,7 @@ predicate isQueryMetadata(Query query, string queryId, string ruleId, string cat
isDeadCode5QueryMetadata(query, queryId, ruleId, category) or
isDeadCode6QueryMetadata(query, queryId, ruleId, category) or
isDeadCode7QueryMetadata(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
33 changes: 32 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,30 @@ 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)
)
}

private Locatable getATypeUse_i(Type type, string reason) {
(
// Restrict to uses within the source checkout root
Expand All @@ -81,6 +107,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 Expand Up @@ -145,6 +172,10 @@ private Locatable getATypeUse_i(Type type, string reason) {
// Temporary object creation of type `type`
exists(TemporaryObjectExpr toe | result = toe | type = toe.getType()) and
reason = "used in temporary object expr"
or
// template<Type t> ...
exists(Declaration decl | result = decl | type = decl.getATemplateArgumentKind()) and
reason = "used as a non-type template parameter"
)
or
// Recursive case - used by a used 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`
}
};
Loading
Loading