1 //===--- NonCopyableObjects.cpp - clang-tidy-------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "NonCopyableObjects.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers
;
16 namespace clang::tidy::misc
{
18 void NonCopyableObjectsCheck::registerMatchers(MatchFinder
*Finder
) {
19 // There are two ways to get into trouble with objects like FILE *:
20 // dereferencing the pointer type to be a non-pointer type, and declaring
21 // the type as a non-pointer type in the first place. While the declaration
22 // itself could technically be well-formed in the case where the type is not
23 // an opaque type, it's highly suspicious behavior.
25 // POSIX types are a bit different in that it's reasonable to declare a
26 // non-pointer variable or data member of the type, but it is not reasonable
27 // to dereference a pointer to the type, or declare a parameter of non-pointer
29 // FIXME: it would be good to make a list that is also user-configurable so
30 // that users can add their own elements to the list. However, it may require
31 // some extra thought since POSIX types and FILE types are usable in different
34 auto BadFILEType
= hasType(
35 namedDecl(hasAnyName("::FILE", "FILE", "std::FILE")).bind("type_decl"));
37 hasType(namedDecl(hasAnyName("::pthread_cond_t", "::pthread_mutex_t",
38 "pthread_cond_t", "pthread_mutex_t"))
40 auto BadEitherType
= anyOf(BadFILEType
, BadPOSIXType
);
43 namedDecl(anyOf(varDecl(BadFILEType
), fieldDecl(BadFILEType
)))
46 Finder
->addMatcher(parmVarDecl(BadPOSIXType
).bind("decl"), this);
48 expr(unaryOperator(hasOperatorName("*"), BadEitherType
)).bind("expr"),
52 void NonCopyableObjectsCheck::check(const MatchFinder::MatchResult
&Result
) {
53 const auto *D
= Result
.Nodes
.getNodeAs
<NamedDecl
>("decl");
54 const auto *BD
= Result
.Nodes
.getNodeAs
<NamedDecl
>("type_decl");
55 const auto *E
= Result
.Nodes
.getNodeAs
<Expr
>("expr");
58 diag(D
->getLocation(), "%0 declared as type '%1', which is unsafe to copy"
59 "; did you mean '%1 *'?")
60 << D
<< BD
->getName();
63 "expression has opaque data structure type %0; type should only be "
64 "used as a pointer and not dereferenced")
68 } // namespace clang::tidy::misc