1 | //===--- ReturnConstRefFromParameterCheck.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 "ReturnConstRefFromParameterCheck.h" |
10 | #include "../utils/Matchers.h" |
11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
12 | #include "clang/ASTMatchers/ASTMatchers.h" |
13 | |
14 | using namespace clang::ast_matchers; |
15 | |
16 | namespace clang::tidy::bugprone { |
17 | |
18 | void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) { |
19 | Finder->addMatcher( |
20 | NodeMatch: returnStmt(hasReturnValue(InnerMatcher: declRefExpr(to(InnerMatcher: parmVarDecl(hasType( |
21 | InnerMatcher: hasCanonicalType(InnerMatcher: matchers::isReferenceToConst()))))))) |
22 | .bind(ID: "ret"), |
23 | Action: this); |
24 | } |
25 | |
26 | void ReturnConstRefFromParameterCheck::check( |
27 | const MatchFinder::MatchResult &Result) { |
28 | const auto *R = Result.Nodes.getNodeAs<ReturnStmt>(ID: "ret"); |
29 | diag(R->getRetValue()->getBeginLoc(), |
30 | "returning a constant reference parameter may cause a use-after-free " |
31 | "when the parameter is constructed from a temporary"); |
32 | } |
33 | |
34 | } // namespace clang::tidy::bugprone |
35 |