1 | //===--- NoexceptSwapCheck.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 "NoexceptSwapCheck.h" |
10 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
11 | |
12 | using namespace clang::ast_matchers; |
13 | |
14 | // FixItHint - comment added to fix list.rst generation in add_new_check.py. |
15 | // Do not remove. Fixes are generated in base class. |
16 | |
17 | namespace clang::tidy::performance { |
18 | |
19 | void NoexceptSwapCheck::registerMatchers(MatchFinder *Finder) { |
20 | |
21 | // Match non-const method with single argument that is non-const reference to |
22 | // a class type that owns method and return void. |
23 | // Matches: void Class::swap(Class&) |
24 | auto MethodMatcher = cxxMethodDecl( |
25 | parameterCountIs(N: 1U), unless(isConst()), returns(InnerMatcher: voidType()), |
26 | hasParameter(N: 0, InnerMatcher: hasType(InnerMatcher: qualType(hasCanonicalType( |
27 | InnerMatcher: qualType(unless(isConstQualified()), |
28 | references(InnerMatcher: namedDecl().bind(ID: "class" ))))))), |
29 | ofClass(InnerMatcher: equalsBoundNode(ID: "class" ))); |
30 | |
31 | // Match function with 2 arguments, both are non-const references to same type |
32 | // and return void. |
33 | // Matches: void swap(Type&, Type&) |
34 | auto FunctionMatcher = allOf( |
35 | unless(cxxMethodDecl()), parameterCountIs(N: 2U), returns(InnerMatcher: voidType()), |
36 | hasParameter( |
37 | N: 0, InnerMatcher: hasType(InnerMatcher: qualType(hasCanonicalType( |
38 | InnerMatcher: qualType(unless(isConstQualified()), references(InnerMatcher: qualType())) |
39 | .bind(ID: "type" ))))), |
40 | hasParameter(N: 1, InnerMatcher: hasType(InnerMatcher: qualType(hasCanonicalType( |
41 | InnerMatcher: qualType(equalsBoundNode(ID: "type" ))))))); |
42 | Finder->addMatcher(NodeMatch: functionDecl(unless(isDeleted()), |
43 | hasAnyName("swap" , "iter_swap" ), |
44 | anyOf(MethodMatcher, FunctionMatcher)) |
45 | .bind(ID: BindFuncDeclName), |
46 | Action: this); |
47 | } |
48 | |
49 | DiagnosticBuilder |
50 | NoexceptSwapCheck::reportMissingNoexcept(const FunctionDecl *FuncDecl) { |
51 | return diag(FuncDecl->getLocation(), "swap functions should " |
52 | "be marked noexcept" ); |
53 | } |
54 | |
55 | void NoexceptSwapCheck::reportNoexceptEvaluatedToFalse( |
56 | const FunctionDecl *FuncDecl, const Expr *NoexceptExpr) { |
57 | diag(Loc: NoexceptExpr->getExprLoc(), |
58 | Description: "noexcept specifier on swap function evaluates to 'false'" ); |
59 | } |
60 | |
61 | } // namespace clang::tidy::performance |
62 | |