68 lines · cpp
1//===----------------------------------------------------------------------===//2//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "NonCopyableObjectsCheck.h"10#include "clang/AST/ASTContext.h"11#include "clang/ASTMatchers/ASTMatchFinder.h"12 13using namespace clang::ast_matchers;14 15namespace clang::tidy::misc {16 17void NonCopyableObjectsCheck::registerMatchers(MatchFinder *Finder) {18 // There are two ways to get into trouble with objects like FILE *:19 // dereferencing the pointer type to be a non-pointer type, and declaring20 // the type as a non-pointer type in the first place. While the declaration21 // itself could technically be well-formed in the case where the type is not22 // an opaque type, it's highly suspicious behavior.23 //24 // POSIX types are a bit different in that it's reasonable to declare a25 // non-pointer variable or data member of the type, but it is not reasonable26 // to dereference a pointer to the type, or declare a parameter of non-pointer27 // type.28 // FIXME: it would be good to make a list that is also user-configurable so29 // that users can add their own elements to the list. However, it may require30 // some extra thought since POSIX types and FILE types are usable in different31 // ways.32 33 auto BadFILEType = hasType(34 namedDecl(hasAnyName("::FILE", "FILE", "std::FILE")).bind("type_decl"));35 auto BadPOSIXType =36 hasType(namedDecl(hasAnyName("::pthread_cond_t", "::pthread_mutex_t",37 "pthread_cond_t", "pthread_mutex_t"))38 .bind("type_decl"));39 auto BadEitherType = anyOf(BadFILEType, BadPOSIXType);40 41 Finder->addMatcher(42 namedDecl(anyOf(varDecl(BadFILEType), fieldDecl(BadFILEType)))43 .bind("decl"),44 this);45 Finder->addMatcher(parmVarDecl(BadPOSIXType).bind("decl"), this);46 Finder->addMatcher(47 expr(unaryOperator(hasOperatorName("*"), BadEitherType)).bind("expr"),48 this);49}50 51void NonCopyableObjectsCheck::check(const MatchFinder::MatchResult &Result) {52 const auto *D = Result.Nodes.getNodeAs<NamedDecl>("decl");53 const auto *BD = Result.Nodes.getNodeAs<NamedDecl>("type_decl");54 const auto *E = Result.Nodes.getNodeAs<Expr>("expr");55 56 if (D && BD)57 diag(D->getLocation(), "%0 declared as type '%1', which is unsafe to copy"58 "; did you mean '%1 *'?")59 << D << BD->getName();60 else if (E)61 diag(E->getExprLoc(),62 "expression has opaque data structure type %0; type should only be "63 "used as a pointer and not dereferenced")64 << BD;65}66 67} // namespace clang::tidy::misc68