1 //===--- TemporaryObjectsCheck.cpp - clang-tidy----------------------------===//
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-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "TemporaryObjectsCheck.h"
10 #include "../utils/OptionsUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include <string>
16
17 using namespace clang::ast_matchers;
18
19 namespace clang::tidy::zircon {
20
AST_MATCHER_P(CXXRecordDecl,matchesAnyName,ArrayRef<StringRef>,Names)21 AST_MATCHER_P(CXXRecordDecl, matchesAnyName, ArrayRef<StringRef>, Names) {
22 std::string QualifiedName = Node.getQualifiedNameAsString();
23 return llvm::is_contained(Names, QualifiedName);
24 }
25
registerMatchers(MatchFinder * Finder)26 void TemporaryObjectsCheck::registerMatchers(MatchFinder *Finder) {
27 // Matcher for default constructors.
28 Finder->addMatcher(
29 cxxTemporaryObjectExpr(hasDeclaration(cxxConstructorDecl(hasParent(
30 cxxRecordDecl(matchesAnyName(Names))))))
31 .bind("temps"),
32 this);
33
34 // Matcher for user-defined constructors.
35 Finder->addMatcher(
36 traverse(TK_AsIs,
37 cxxConstructExpr(hasParent(cxxFunctionalCastExpr()),
38 hasDeclaration(cxxConstructorDecl(hasParent(
39 cxxRecordDecl(matchesAnyName(Names))))))
40 .bind("temps")),
41 this);
42 }
43
check(const MatchFinder::MatchResult & Result)44 void TemporaryObjectsCheck::check(const MatchFinder::MatchResult &Result) {
45 if (const auto *D = Result.Nodes.getNodeAs<CXXConstructExpr>("temps"))
46 diag(D->getLocation(),
47 "creating a temporary object of type %q0 is prohibited")
48 << D->getConstructor()->getParent();
49 }
50
storeOptions(ClangTidyOptions::OptionMap & Opts)51 void TemporaryObjectsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
52 Options.store(Opts, "Names", utils::options::serializeStringList(Names));
53 }
54
55 } // namespace clang::tidy::zircon
56