clang-tools 19.0.0git
ReturnConstRefFromParameterCheck.cpp
Go to the documentation of this file.
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
10#include "../utils/Matchers.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::bugprone {
17
19 Finder->addMatcher(
20 returnStmt(
21 hasReturnValue(declRefExpr(to(parmVarDecl(hasType(hasCanonicalType(
22 qualType(matchers::isReferenceToConst()).bind("type"))))))),
23 hasAncestor(functionDecl(hasReturnTypeLoc(
24 loc(qualType(hasCanonicalType(equalsBoundNode("type"))))))))
25 .bind("ret"),
26 this);
27}
28
30 const MatchFinder::MatchResult &Result) {
31 const auto *R = Result.Nodes.getNodeAs<ReturnStmt>("ret");
32 const SourceRange Range = R->getRetValue()->getSourceRange();
33 if (Range.isInvalid())
34 return;
35 diag(Range.getBegin(),
36 "returning a constant reference parameter may cause use-after-free "
37 "when the parameter is constructed from a temporary")
38 << Range;
39}
40
41} // namespace clang::tidy::bugprone
CharSourceRange Range
SourceRange for the file name.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.